2013-03-22 163 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