我试图通过JavaScript阻止浏览器使用CSS的:hover效果.

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

我试过这个:

$("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/).我正在寻找一个通用的解决方案.

有人知道怎么做吗?

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

推荐答案

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

不过,您可以try 以下替代解决方案.如果你不介意在你的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');
)

Jquery相关问答推荐

将选定2个AJAX结果显示到模板中

使用 jQuery 时何时/为什么要在变量前加上$?

jQuery获取DOM node ?

在jQuery中获取所有选定复选框值的最佳方法

jQuery Keypress 箭头键

JQuery手风琴自动高度问题

调用 jquery ajax - .fail vs. :error

Angular.js 在多个元素中重复

调用 e.preventDefault() 后提交表单

将参数附加到 URL 而不刷新

从父 node 中删除所有子 node ?

点击时保持 Bootstrap 下拉菜单打开

将图像 url 转换为 Base64

用 Javascript 加载 jQuery 并使用 jQuery

虽然未定义变量 - 等待

我如何知道 jQuery 是否有待处理的 Ajax 请求?

消除移动 Safari 中点击事件的 300 毫秒延迟

如何防止使用光标拖动 Select 文本/元素

如果一个元素正在被动画,我如何用 jQuery 找出?

jQuery clone() 不克隆事件绑定,即使使用 on()