2013-03-22 159 views
15

我有一個頁面上的一些圖片,我現在用的是以下觸發事件:如何將延遲添加到jquery mouseover?

$('.img').on('mouseover', function() { 
//do something 

}); 

是否有某種方式來增加延遲,例如,如果用戶將鼠標懸停於也許1秒,那麼它「//做些什麼」或實際觸發「鼠標懸停」事件?

+0

退房setTimeout和clearTimeout。 – j08691 2013-03-22 17:03:26

回答

32

您可以使用setTimeout

var delay=1000, setTimeoutConst; 
    $('.img').on('hover', function() { 
     setTimeoutConst = setTimeout(function(){ 
       //do something 
     }, delay); 
    }, function(){ 
     clearTimeout(setTimeoutConst); 

     }); 
+10

這不會捕獲意圖。如果用戶懸停,然後鼠標離開它,我希望它實際上不執行setTimeout中的內容。 – Rolando 2013-03-22 19:48:12

+0

我改變了代碼檢查是否可以解決你的問題 – Anoop 2013-03-22 19:50:20

+0

這個setTimeout函數內部似乎改變了,不再是函數影響的DOM對象,而是窗口/全局對象,所以我寫的函數停止工作。 – 2014-08-24 02:57:39

1

使用一個計時器,並清除它時,他們鼠標移出櫃面他們離開內1000ms的

var timer; 

$('.img').on({ 
    'mouseover': function() { 
     timer = setTimeout(function() { 
      // do stuff 
     }, 1000); 
    }, 
    'mouseout' : function() { 
     clearTimeout(timer); 
    } 
}); 
19

你可以做的是使用沿着setTimeoutclearTimeout如果用戶葉子太快了:

var timer; 
var delay = 1000; 

$('#element').hover(function() { 
    // on mouse in, start a timeout 

    timer = setTimeout(function() { 
     // do your stuff here 
    }, delay); 
}, function() { 
    // on mouse out, cancel the timer 
    clearTimeout(timer); 
}); 
+0

這很清楚爲什麼兩個函數被傳入懸停函數,並且每個函數都被調用。 – 2014-11-06 19:41:12

1

您可以使用jQuery .Delay這樣的(未測試):

$("#test").hover(
    function() { 
     $(this).delay(800).fadeIn(); 
    } 
); 

http://api.jquery.com/delay/

+1

請注意'$(selector).delay()'只能用於動畫。 – 2014-05-12 17:39:05

3

我一直在尋找這樣的事情爲好,但與次延遲爲好。我在這裏選擇了其中一個答案並在其上擴展

此示例顯示鼠標懸停X秒後的div,並在鼠標懸停X秒後隱藏它。但如果將鼠標懸停在所顯示的div上,則禁用。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<style type="text/css"> 
.foo{ 
    position:absolute; display:none; padding:30px; 
    border:1px solid black; background-color:white; 
} 
</style> 
<h3 class="hello"> 
    <a href="#">Hello, hover over me 
    <span class="foo">foo text</span> 
    </a> 
</h3> 


<script type="text/javascript"> 
var delay = 1500, setTimeoutConst, 
    delay2 = 500, setTimeoutConst2; 
$(".hello").mouseover(function(){ 
    setTimeoutConst = setTimeout(function(){ 
    $('.foo').show(); 
    },delay); 
}).mouseout(function(){ 
    clearTimeout(setTimeoutConst); 
    setTimeoutConst2 = setTimeout(function(){ 
    var isHover = $('.hello').is(":hover"); 
    if(isHover !== true){ 
     $('.foo').hide(); 
    } 
    },delay2); 
}); 
</script> 

Working example