1

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?

4

2 回答 2

2
$("#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");
});

第二个处理程序是“悬停”,尽管它可能会更好地使用以下内容:

//  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

更多关于:

于 2013-05-23T12:18:20.987 回答
1

您可以通过使用 mouseenter 和 mouseleave 而不是悬停来做到这一点

$("#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"); 
});
于 2013-05-23T12:18:30.437 回答