remove/unbind hover on anchors

为君一笑 提交于 2019-12-10 18:17:59

问题


html

<a href="home.html">Home</a>

css

a {
   color: blue;
}
a:hover {
   color: red;
}

now as you can see <a> now would be color red on hover.

Question
How do I remove hover via jQuery?
I have tried: $('a').unbind('hover'); and $('a').unbind('mouseenter mouseleave')

I come to think why it won't work, is this not hover()?


回答1:


Since a:hover is not bound event on the anchor tag and is only a pseudo class you won't have success unbinding the .hover() event.

If you want to change the behavior then you can do two things

  1. remove the a:hover styles

  2. bind a hover event on the anchor tag and set the css accordingly.




回答2:


No. This is a CSS rule, not a JavaScript event.
The easiest way to change the color is via a stronger CSS rule, for example:

a.NoHover:hover {
   color: blue;
}

or

body a:hover {
   color: blue;
}



回答3:


You can add/remove classes and use JQuery to act accordingly. So you should create classes for both normal and hover state. For example, you can remove styling from the element like this:

$('a').mouseover(function(){
  $(this).removeClass();
});

But I would suggest you to actually add and remove classes accordingly using:

addClass()
removeClass()




回答4:


If its only color you are concerned about this might help.

$('a').each(function() {
   var $this = $(this);
   $this.css('color', $this.css('color'));
 });

The element's style property will override the properties set in any CSS selectors. The theory has been tested and works fine. This plugin will read arbitrary css properties and set them back therefore "sticking" them.

$.fn.stickCss = function(props) {
  var stick = (props || '').split(/\s+/);
  return this.each(function() {
    var $this = $(this);
    $.each(stick, function(i, prop) {
      $this.css(prop, $this.css(prop));
    });
  });
};

// example usage:
$('a').stickCss('color background-color margin padding');


来源:https://stackoverflow.com/questions/2688701/remove-unbind-hover-on-anchors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!