Add class when hovered NOT over any of the group of elements

ぃ、小莉子 提交于 2019-12-11 11:39:14

问题


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.

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");
});

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?


回答1:


$("#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

More About:

  • .hover()
    • Don't forget, this method has up to 2 handlers!
  • .mouseleave()
    • See Also: mouseleave vs
  • jQuery Chaining



回答2:


You could do this by using mouseenter and mouseleave instead of hover

$("#container").find("a").eq(random).addClass("active"); 
$("#container a").mouseenter(function() {
     $("container a.active").removeClass("active");
});
$("#container a").mouseleave(function() {
     $("#container").find("a").eq(random).addClass("active"); 
});


来源:https://stackoverflow.com/questions/16713676/add-class-when-hovered-not-over-any-of-the-group-of-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!