我可以通过JavaScript禁用CSS:hover效果吗? [英] Can I disable a CSS :hover effect via JavaScript?

查看:91
本文介绍了我可以通过JavaScript禁用CSS:hover效果吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我已经在我的CSS中设置了 a a:hover 样式,因为我想要一个悬停效果,if JS不可用。但是如果JS 是可用的,我想用一个更平滑的覆盖我的CSS悬停效果(例如使用jQuery颜色插件)。



我尝试这样:

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

我也尝试过 return false; ,但不起作用。



这是我的问题的示例: http://jsfiddle.net/4rEzz/



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



有没有人知道如何做?



PS : :我不想覆盖已为悬停设置的每个样式。纯JavaScript通用解决方案,恐怕。 JavaScript无法关闭CSS :hover 状态本身。



您可以尝试以下替代解决方法虽然。如果你不介意在你的HTML和CSS一点点,它节省你不得不通过JavaScript手动重置每个CSS属性。



HTML



 < body class =nojQuery> 



CSS



  / *限制CSS中的悬停样式,以便它们只适用于存在nojQuery 
类时* /

body.nojQuery ul#mainFilter a:hover {
/ *仅限CSS的悬停样式在此处* /
}



h3>

  //当jQuery启动时,从< body>元素,因此
//使CSS悬浮样式消失。

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


I’m trying to prevent the browser from using the :hover effect of the CSS, via 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.)

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.

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.

Does anyone know how to do this?

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.

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

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

这篇关于我可以通过JavaScript禁用CSS:hover效果吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆