JavaScript를 통해 CSS : hover 효과를 비활성화 할 수 있습니까?
브라우저가 :hover
JavaScript를 통해 CSS 의 효과 를 사용하지 못하도록하려고합니다 .
JS를 사용할 수없는 경우 호버 효과를 원하기 때문에 CSS에서 a
및 a:hover
스타일을 설정했습니다 . 그러나 JS 를 사용할 수있는 경우 CSS 호버 효과를 더 부드러운 효과로 덮어 쓰고 싶습니다 (예 : jQuery 색상 플러그인 사용).
나는 이것을 시도했다 :
$("ul#mainFilter a").hover(
function(e){ e.preventDefault(); ...do my stuff... },
function(e){ e.preventDefault(); ...do my stuff... });
나는 또한 그것을 시도했지만 return false;
작동하지 않습니다.
다음은 내 문제의 예입니다. http://jsfiddle.net/4rEzz/ . 링크는 회색이되지 않고 희미 해져야합니다.
fudgey에서 언급했듯이 해결 방법은를 사용하여 호버 스타일을 재설정하는 .css()
것이지만 CSS에 지정된 모든 단일 속성을 덮어 써야 합니다 (여기 참조 : http://jsfiddle.net/raPeX/1/ ). 일반적인 솔루션을 찾고 있습니다.
누구든지 이것을하는 방법을 알고 있습니까?
추신 : 호버링에 대해 설정 한 모든 스타일을 덮어 쓰고 싶지 않습니다.
순수한 JavaScript 제네릭 솔루션은 없습니다. 두렵습니다. JavaScript는 CSS :hover
상태 자체 를 끌 수 없습니다 .
그래도 다음 대체 해결 방법을 시도 할 수 있습니다. HTML과 CSS에 대해 조금이라도 신경 쓰지 않는다면 JavaScript를 통해 모든 CSS 속성을 수동으로 재설정 할 필요가 없습니다.
HTML
<body class="nojQuery">
CSS
/* Limit the hover styles in your CSS so that they only apply when the nojQuery
class is present */
body.nojQuery ul#mainFilter a:hover {
/* CSS-only hover styles go here */
}
자바 스크립트
// When jQuery kicks in, remove the nojQuery class from the <body> element, thus
// making the CSS hover styles disappear.
$(function(){}
$('body').removeClass('nojQuery');
)
호버 만 할당 된 두 번째 클래스를 사용하십시오.
HTML
<a class="myclass myclass_hover" href="#">My anchor</a>
CSS
.myclass {
/* all anchor styles */
}
.myclass_hover:hover {
/* example color */
color:#00A;
}
이제 Jquery를 사용하여 클래스를 제거 할 수 있습니다 (예 : 요소를 클릭 한 경우).
JQUERY
$('.myclass').click( function(e) {
e.preventDefault();
$(this).removeClass('myclass_hover');
});
이 답변이 도움이 되었기를 바랍니다.
자바 스크립트로 스타일 시트와 스타일 시트 규칙을 직접 조작 할 수 있습니다.
var sheetCount = document.styleSheets.length;
var lastSheet = document.styleSheets[sheetCount-1];
var ruleCount;
if (lastSheet.cssRules) { // Firefox uses 'cssRules'
ruleCount = lastSheet.cssRules.length;
}
else if (lastSheet.rules) { / /IE uses 'rules'
ruleCount = lastSheet.rules.length;
}
var newRule = "a:hover { text-decoration: none !important; color: #000 !important; }";
// insert as the last rule in the last sheet so it
// overrides (not overwrites) previous definitions
lastSheet.insertRule(newRule, ruleCount);
속성을 중요하게 만들고 이것을 마지막 CSS 정의로 만들면 더 구체적으로 대상이 지정되지 않는 한 이전 정의를 재정의해야합니다. 이 경우 더 많은 규칙을 삽입해야 할 수 있습니다.
이것은 aSeptik의 답변과 유사하지만이 접근 방식은 어떻습니까? JavaScript 사용을 비활성화하려는 CSS 코드를 <noscript>
태그로 래핑합니다 . 이렇게하면 javaScript가 꺼져 있으면 CSS :hover
가 사용되고 그렇지 않으면 JavaScript 효과가 사용됩니다.
예:
<noscript>
<style type="text/css">
ul#mainFilter a:hover {
/* some CSS attributes here */
}
</style>
</noscript>
<script type="text/javascript">
$("ul#mainFilter a").hover(
function(o){ /* ...do your stuff... */ },
function(o){ /* ...do your stuff... */ });
</script>
CSS를 사용하여 : hover 이벤트가 링크의 모양을 변경하지 않도록합니다.
a{
font:normal 12px/15px arial,verdana,sans-serif;
color:#000;
text-decoration:none;
}
This simple CSS means that the links will always be black and not underlined. I cannot tell from the question whether the change in the appearance is the only thing you want to control.
I'd recommend to replace all :hover
properties to :active
when you detect that device supports touch. Just call this function when you do so as touch()
.
function touch() {
if ('ontouchstart' in document.documentElement) {
for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
var sheet = document.styleSheets[sheetI];
if (sheet.cssRules) {
for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
var rule = sheet.cssRules[ruleI];
if (rule.selectorText) {
rule.selectorText = rule.selectorText.replace(':hover', ':active');
}
}
}
}
}
}
I used the not()
CSS operator and jQuery's addClass()
function. Here is an example, when you click on a list item, it won't hover anymore:
For example:
HTML
<ul class="vegies">
<li>Onion</li>
<li>Potato</li>
<li>Lettuce</li>
<ul>
CSS
.vegies li:not(.no-hover):hover { color: blue; }
jQuery
$('.vegies li').click( function(){
$(this).addClass('no-hover');
});
Try just setting the link color:
$("ul#mainFilter a").css('color','#000');
Edit: or better yet, use the CSS, as Christopher suggested
Actually an other way to solve this could be, overwriting the CSS with insertRule
.
It gives the ability to inject CSS rules to an existing/new stylesheet. In my concrete example it would look like this:
//creates a new `style` element in the document
var sheet = (function(){
var style = document.createElement("style");
// WebKit hack :(
style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.head.appendChild(style);
return style.sheet;
})();
//add the actual rules to it
sheet.insertRule(
"ul#mainFilter a:hover { color: #0000EE }" , 0
);
Demo with my 4 years old original example: http://jsfiddle.net/raPeX/21/
참고URL : https://stackoverflow.com/questions/2754546/can-i-disable-a-css-hover-effect-via-javascript
'Programing' 카테고리의 다른 글
경도 \ 위도에서 데카르트 좌표로 변환 (0) | 2020.08.28 |
---|---|
Bash, 인수 없음 경고 및 케이스 결정 (0) | 2020.08.28 |
데이터 프레임 전치 (0) | 2020.08.28 |
모든 자바 스크립트 처리되지 않은 예외 잡기 (0) | 2020.08.28 |
ffmpeg를 사용하여 프레임을 추출하는 가장 빠른 방법은 무엇입니까? (0) | 2020.08.28 |