2013-09-23 13 views
8

Chciałbym dodać i usunąć klasy na elementach, gdy użytkownik unosi się nad elementem, ale tylko wtedy, gdy na przykład kursor był na nim przez ponad 1 sekundę. Jak mogę to osiągnąć?Funkcję wykonuję tylko wtedy, gdy mysz unosi się przez ponad sekundę.

$("#thumbs div").mouseenter(function() { 
    $('#thumbs div').removeClass('hovered'); 
    $(this).addClass('hovered'); 
}); 
+1

użyj 'setTimeout' i' clearTimeout'. – meagar

+0

Istnieje hoverintent plugin, który służy temu celowi. –

Odpowiedz

25

Użyj Timer:

var timer; 
$("#thumbs div").mouseenter(function() { 
    var that = this; 
    timer = setTimeout(function(){ 
     $('#thumbs div').removeClass('hovered'); 
     $(that).addClass('hovered'); 
    }, 1000); 
}).mouseleave(function() { 
    clearTimeout(timer); 
}); 

http://jsfiddle.net/qGRcH/

0

http://jsfiddle.net/bSuuy/2/

var timer; 

$("button").on("mouseenter", function() { 
    timer = setTimeout(function() { 
     $(".box").css("background", "blue"); 
    }, 1000); 
}); 

$("button").on("mouseout", function() { 
    $(".box").css("background", "red"); 
    clearTimeout(timer); 
}); 
+1

Myślę, że musi to być clearTimeout – ysrb

1

można użyć najechania kursorem i opóźnienia:

$("#thumbs div").hover(function() { 
    $(this).delay(1000).queue(function(){ 
     $(this).addClass('hovered').siblings().removeClass('hovered'); 
    }); 
},function() { 
    $(this).finish(); 
}); 
Powiązane problemy