如何强制使用jQuery的悬停状态? [英] How to force a hover state with jQuery?

查看:70
本文介绍了如何强制使用jQuery的悬停状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意这个CSS代码:

Please, considere this CSS code:

a { color: #ffcc00; }
a:hover { color: #ccff00; }

此HTML代码:

<a href="#" id="link">Link</a>
<button id="btn">Click here</button>

最后,这个JS代码:

$("#btn").click(function() {
   $("#link").trigger("hover");
});

我想让我的链接使用它的伪类:hover当点击按钮。
我试图触发事件,如mousemove,mouseenter,hover等,但任何人都工作。
注意,我想强制使用我的CSS伪类:hover规范,不使用类似:

I would like to make my link uses its pseudo-class :hover when the button is clicked. I tried to trigger events like mousemove, mouseenter, hover etc, but anyone works. Notice that I want to force the use of the my CSS pseudo-class :hover specification and not use something like:

$("#link").css("color", "ccff00");

有人知道我该怎么办?非常感谢。

Some one know how do I do this? Thank you a lot.

推荐答案

您必须使用类,但不要担心,这很简单。首先,我们将分配:hover 规则,不仅适用于物理悬浮链接,还适用于类名 hover的链接

You will have to use a class, but don't worry, it's pretty simple. First we'll assign your :hover rules to not only apply to physically-hovered links, but also to links that have the classname hovered.

a:hover, a.hovered { color: #ccff00; }

接下来,当您单击 #btn ,我们将切换 #link 上的 .hovered 类。

Next, when you click #btn, we'll toggle the .hovered class on the #link.

$("#btn").click(function() {
   $("#link").toggleClass("hovered");
});

如果链接已经有类,它将被删除。如果没有类,它将被添加。

If the link has the class already, it will be removed. If it doesn't have the class, it will be added.

这篇关于如何强制使用jQuery的悬停状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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