如何使用 jQuery 强制悬停状态?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2290829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to force a hover state with jQuery?
提问by MCardinale
Please, considere this CSS code:
请考虑这个 CSS 代码:
a { color: #ffcc00; }
a:hover { color: #ccff00; }
This HTML code:
此 HTML 代码:
<a href="#" id="link">Link</a>
<button id="btn">Click here</button>
And, finally, this JS code:
最后,这段 JS 代码:
$("#btn").click(function() {
$("#link").trigger("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:
我想让我的链接在单击按钮时使用其伪类 :hover。我试图触发诸如 mousemove、mouseenter、hover 等事件,但任何人都可以工作。请注意,我想强制使用我的 CSS 伪类 :hover 规范,而不是使用以下内容:
$("#link").css("color", "ccff00");
Some one know how do I do this? Thank you a lot.
有人知道我该怎么做吗?非常感谢。
回答by Sampson
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
.
你将不得不使用一个类,但别担心,它很简单。首先,我们将分配您的:hover
规则,不仅适用于物理悬停的链接,还适用于具有 classname 的链接hovered
。
a:hover, a.hovered { color: #ccff00; }
Next, when you click #btn
, we'll toggle the .hovered
class on the #link
.
接下来,当您单击 时#btn
,我们将在.hovered
上切换类#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.
如果链接已经有类,它将被删除。如果它没有类,它将被添加。
回答by Mike
Also, you could try triggering a mouseover.
此外,您可以尝试触发鼠标悬停。
$("#btn").click(function() {
$("#link").trigger("mouseover");
});
Not sure if this will work for your specific scenario, but I've had success triggering mouseover instead of hover for various cases.
不确定这是否适用于您的特定场景,但我已经成功触发鼠标悬停而不是在各种情况下悬停。
回答by Digggid
I think the best solution I have come across is on this stackoverflow.
This short jQuery code allows all your hover effects to show on click or touch..
No need to add anything within the function.
我认为我遇到的最好的解决方案是在这个stackoverflow 上。这段简短的 jQuery 代码允许您在单击或触摸时显示所有悬停效果。
无需在函数中添加任何内容。
$('body').on('touchstart', function() {});
Hope this helps.
希望这可以帮助。