Add class when hovered NOT over any of the group o

2019-08-08 16:45发布

问题:

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