我有一个页面上的一些图片,我现在用的是以下触发事件:如何将延迟添加到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