我可以禁用CSS:悬停效果通过JavaScript吗?

时间:2022-11-05 13:49:01

I’m trying to prevent the browser from using the :hover effect of the CSS, via JavaScript.

我试图阻止浏览器使用:CSS的悬浮效果,通过JavaScript。

I have set the a and a:hover styles in my CSS, because I want a hover effect, if JS isn’t available. But if JS is available, I want to overwrite my CSS hover effect with a smoother one (using the jQuery color plugin for example.)

我在我的CSS中设置了a和a:hover样式,因为我想要一个悬浮效果,如果没有JS。但是如果JS是可用的,我想用更平滑的方法覆盖我的CSS鼠标悬停效果(例如,使用jQuery颜色插件)。

I tried this:

我试着这样的:

$("ul#mainFilter a").hover(
     function(e){ e.preventDefault(); ...do my stuff... }, 
     function(e){ e.preventDefault(); ...do my stuff... });

I also tried it with return false;, but it does not work.

我也试过了,但它不起作用。

Here is an example of my problem: http://jsfiddle.net/4rEzz/. The link should just fade without getting gray.

下面是我的一个示例:http://jsfiddle.net/4rEzz/。链接应该只是淡出而不会变灰。

As mentioned by fudgey, a workaround would be to reset the hover styles using .css() but I would have to overwrite every single property, specified in the CSS (see here: http://jsfiddle.net/raPeX/1/ ). I am looking for a generic solution.

正如fudgey所提到的,一个解决方案是使用. CSS()来重置悬浮样式,但是我必须覆盖在CSS中指定的每一个属性(参见http://jsfiddle.net/raPeX/1/)。我在寻找一个通用的解决方案。

Does anyone know how to do this?

有人知道怎么做吗?

PS: I do not want to overwrite every style i have set for the hover.

PS:我不想覆盖我设置的每一个样式。

9 个解决方案

#1


127  

There isn’t a pure JavaScript generic solution, I’m afraid. JavaScript isn’t able to turn off the CSS :hover state itself.

恐怕没有一个纯粹的JavaScript通用解决方案。JavaScript无法关闭CSS:hover状态本身。

You could try the following alternative workaround though. If you don’t mind mucking about in your HTML and CSS a little bit, it saves you having to reset every CSS property manually via JavaScript.

不过,您可以尝试下面的替代方法。如果你不介意在你的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 */
}

JavaScript

// When jQuery kicks in, remove the nojQuery class from the <body> element, thus
// making the CSS hover styles disappear.

$(function(){}
    $('body').removeClass('nojQuery');
)

#2


11  

You can manipulate the stylesheets and stylesheet rules themselves with javascript

您可以使用javascript操作样式表和样式表。

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);

Making the attributes !important and making this the very last CSS definition should override any previous definition, unless one is more specifically targeted. You may have to insert more rules in that case.

重要的是,这是最后一个CSS定义,它应该覆盖任何之前的定义,除非其中一个是更明确的目标。在这种情况下,您可能需要插入更多的规则。

#3


10  

This is similar to aSeptik's answer, but what about this approach? Wrap the CSS code which you want to disable using JavaScript in <noscript> tags. That way if javaScript is off, the CSS :hover will be used, otherwise the JavaScript effect will be used.

这类似于aSeptik的答案,但是这个方法呢?在

Example:

例子:

<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>

#4


10  

Just a shorter answer...

只是一个短的答案……

Use a second class that has only the hover assigned:

使用只指定了鼠标悬停的第二个类:

HTML

HTML

 <a class="myclass myclass_hover" href="#">My anchor</a>

CSS

CSS

 .myclass { 
   /* all anchor styles */
 }
 .myclass_hover:hover {
   /* example color */
   color:#00A;
 }

Now you can use Jquery to remove the class, for instance if the element has been clicked:

现在可以使用Jquery来删除类,例如,如果已经单击了元素:

JQUERY

JQUERY

 $('.myclass').click( function(e) {
    e.preventDefault();
    $(this).removeClass('myclass_hover');
 });

Hope this answer is helpful.

希望这个答案是有用的。

#5


3  

I would use CSS to prevent the :hover event from changing the appearance of the link.

我将使用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.

这个简单的CSS意味着链接永远是黑色的,没有下划线。我无法从这个问题中看出,外观的变化是否是你唯一想要控制的东西。

#6


2  

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:

我使用了not() CSS操作符和jQuery的addClass()函数。这里有一个例子,当你点击一个列表项,它就不再盘旋了:

For example:

例如:

HTML

HTML

<ul class="vegies">
    <li>Onion</li>
    <li>Potato</li>
    <li>Lettuce</li>
<ul>

CSS

CSS

.vegies li:not(.no-hover):hover { color: blue; }

jQuery

jQuery

$('.vegies li').click( function(){
    $(this).addClass('no-hover');
});

#7


1  

Try just setting the link color:

尝试设置链接颜色:

$("ul#mainFilter a").css('color','#000');

Edit: or better yet, use the CSS, as Christopher suggested

编辑:或者更好的是,像克里斯托弗建议的那样使用CSS。

#8


1  

Actually an other way to solve this could be, overwriting the CSS with insertRule.

实际上,另一种解决方法是,用insertRule覆盖CSS。

It gives the ability to inject CSS rules to an existing/new stylesheet. In my concrete example it would look like this:

它提供了向现有/新样式表注入CSS规则的能力。在我的具体例子中,它是这样的:

//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/

演示与我的4年原始示例:http://jsfiddle.net/raPeX/21/。

#9


1  

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().

我建议替换所有的:hover属性到:当你检测到设备支持触摸时,激活。当您使用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');
          }
        }
      }
    }
  }
}

#1


127  

There isn’t a pure JavaScript generic solution, I’m afraid. JavaScript isn’t able to turn off the CSS :hover state itself.

恐怕没有一个纯粹的JavaScript通用解决方案。JavaScript无法关闭CSS:hover状态本身。

You could try the following alternative workaround though. If you don’t mind mucking about in your HTML and CSS a little bit, it saves you having to reset every CSS property manually via JavaScript.

不过,您可以尝试下面的替代方法。如果你不介意在你的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 */
}

JavaScript

// When jQuery kicks in, remove the nojQuery class from the <body> element, thus
// making the CSS hover styles disappear.

$(function(){}
    $('body').removeClass('nojQuery');
)

#2


11  

You can manipulate the stylesheets and stylesheet rules themselves with javascript

您可以使用javascript操作样式表和样式表。

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);

Making the attributes !important and making this the very last CSS definition should override any previous definition, unless one is more specifically targeted. You may have to insert more rules in that case.

重要的是,这是最后一个CSS定义,它应该覆盖任何之前的定义,除非其中一个是更明确的目标。在这种情况下,您可能需要插入更多的规则。

#3


10  

This is similar to aSeptik's answer, but what about this approach? Wrap the CSS code which you want to disable using JavaScript in <noscript> tags. That way if javaScript is off, the CSS :hover will be used, otherwise the JavaScript effect will be used.

这类似于aSeptik的答案,但是这个方法呢?在

Example:

例子:

<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>

#4


10  

Just a shorter answer...

只是一个短的答案……

Use a second class that has only the hover assigned:

使用只指定了鼠标悬停的第二个类:

HTML

HTML

 <a class="myclass myclass_hover" href="#">My anchor</a>

CSS

CSS

 .myclass { 
   /* all anchor styles */
 }
 .myclass_hover:hover {
   /* example color */
   color:#00A;
 }

Now you can use Jquery to remove the class, for instance if the element has been clicked:

现在可以使用Jquery来删除类,例如,如果已经单击了元素:

JQUERY

JQUERY

 $('.myclass').click( function(e) {
    e.preventDefault();
    $(this).removeClass('myclass_hover');
 });

Hope this answer is helpful.

希望这个答案是有用的。

#5


3  

I would use CSS to prevent the :hover event from changing the appearance of the link.

我将使用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.

这个简单的CSS意味着链接永远是黑色的,没有下划线。我无法从这个问题中看出,外观的变化是否是你唯一想要控制的东西。

#6


2  

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:

我使用了not() CSS操作符和jQuery的addClass()函数。这里有一个例子,当你点击一个列表项,它就不再盘旋了:

For example:

例如:

HTML

HTML

<ul class="vegies">
    <li>Onion</li>
    <li>Potato</li>
    <li>Lettuce</li>
<ul>

CSS

CSS

.vegies li:not(.no-hover):hover { color: blue; }

jQuery

jQuery

$('.vegies li').click( function(){
    $(this).addClass('no-hover');
});

#7


1  

Try just setting the link color:

尝试设置链接颜色:

$("ul#mainFilter a").css('color','#000');

Edit: or better yet, use the CSS, as Christopher suggested

编辑:或者更好的是,像克里斯托弗建议的那样使用CSS。

#8


1  

Actually an other way to solve this could be, overwriting the CSS with insertRule.

实际上,另一种解决方法是,用insertRule覆盖CSS。

It gives the ability to inject CSS rules to an existing/new stylesheet. In my concrete example it would look like this:

它提供了向现有/新样式表注入CSS规则的能力。在我的具体例子中,它是这样的:

//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/

演示与我的4年原始示例:http://jsfiddle.net/raPeX/21/。

#9


1  

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().

我建议替换所有的:hover属性到:当你检测到设备支持触摸时,激活。当您使用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');
          }
        }
      }
    }
  }
}