将鼠标悬停在任何元素组上时添加类 [英] Add class when hovered NOT over any of the group of elements

查看:338
本文介绍了将鼠标悬停在任何元素组上时添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在#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");

jsFiddle

更多关于:

  • .hover()
    • 别忘了,此方法最多具有 2 个处理程序!
    • .hover()
      • Don't forget, this method has up to 2 handlers!

      这篇关于将鼠标悬停在任何元素组上时添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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