将鼠标悬停在任何元素组上时添加类 [英] Add class when hovered NOT over any of the group of elements
问题描述
我在#container
中有一堆锚标签.我正在使用jQuery选择随机锚标记,并向其中添加.active
类.
I have a bunch of anchor tags inside a #container
. I am selecting a random anchor tag with jQuery and adding an .active
class to it.
然后,当用户将鼠标悬停在这些锚点标签中的任何一个上时,.active类就会从当前拥有的锚类中删除:
Then, when a user hovers over any of these anchor tags, the .active class gets removed from the one that currently has it:
$("#container").find("a").eq(random).addClass("active");
$("#container a").hover(function() {
$("container a.active").removeClass("active");
});
我想再添加一件事.如果用户没有将鼠标悬停在#container
内的任何链接上,我想再次将.active
类添加到#container
内的任何随机锚标签.我怎样才能做到这一点?
I want to add one more thing to this. If a user hovers NOT over any of the links inside the #container
, I want to add the .active
class again to any random anchor tag inside the #container
. How can I do that?
推荐答案
$("#container").find("a").eq(random).addClass("active");
$("#container a").hover(function() {
$("container a.active").removeClass("active");
},
function(e) {
$("#container").find("a").eq(random).addClass("active");
});
第二个处理程序是悬停"的,尽管它在以下情况下可能会更好地工作:
The second handler is "hover out", though it would probably work better with something like:
// begin working on parent container
// .mouseleave allows us to know exactly,
// on a single event fire,
// when mouse has left the parent container
$("#container").on("mouseleave", function(e) {
// of course, add class to random anchor
$(this).find("a").eq(random).addClass("active");
}) // jQuery Chaining allows us to then move on forward to the a tags
.find("a").hover(function() { // upon hover, remove ALL instances of "active" class
$("#container a.active").removeClass("active");
}) // our returned Object is the same as "$("#container").find("a")"
.eq(random).addClass("active");
更多关于:
- .hover()
- 别忘了,此方法最多具有 2 个处理程序!
- .hover()
- Don't forget, this method has up to 2 handlers!
- 另请参见: mouseleave vs
这篇关于将鼠标悬停在任何元素组上时添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!