我有一個頁面上的一些圖片,我現在用的是以下觸發事件:如何將延遲添加到jquery mouseover?
$('.img').on('mouseover', function() {
//do something
});
是否有某種方式來增加延遲,例如,如果用戶將鼠標懸停於也許1秒,那麼它「//做些什麼」或實際觸發「鼠標懸停」事件?
我有一個頁面上的一些圖片,我現在用的是以下觸發事件:如何將延遲添加到jquery mouseover?
$('.img').on('mouseover', function() {
//do something
});
是否有某種方式來增加延遲,例如,如果用戶將鼠標懸停於也許1秒,那麼它「//做些什麼」或實際觸發「鼠標懸停」事件?
您可以使用setTimeout
var delay=1000, setTimeoutConst;
$('.img').on('hover', function() {
setTimeoutConst = setTimeout(function(){
//do something
}, delay);
}, function(){
clearTimeout(setTimeoutConst);
});
使用一個計時器,並清除它時,他們鼠標移出櫃面他們離開內1000ms的
var timer;
$('.img').on({
'mouseover': function() {
timer = setTimeout(function() {
// do stuff
}, 1000);
},
'mouseout' : function() {
clearTimeout(timer);
}
});
你可以做的是使用沿着setTimeout
有clearTimeout
如果用戶葉子太快了:
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);
});
這很清楚爲什麼兩個函數被傳入懸停函數,並且每個函數都被調用。 – 2014-11-06 19:41:12
您可以使用jQuery .Delay這樣的(未測試):
$("#test").hover(
function() {
$(this).delay(800).fadeIn();
}
);
請注意'$(selector).delay()'只能用於動畫。 – 2014-05-12 17:39:05
我一直在尋找這樣的事情爲好,但與次延遲爲好。我在這裏選擇了其中一個答案並在其上擴展
此示例顯示鼠標懸停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>
退房setTimeout和clearTimeout。 – j08691 2013-03-22 17:03:26