2010-07-25 147 views
20
$('.file a').live('mouseenter', function() { 
    $('#download').stop(true, true).fadeIn('fast'); 
}).live('mouseleave', function() { 
    $('#download').stop(true, true).fadeOut('fast'); 
}); 

我希望mouseenter函数的stop()和延迟1秒。 因此,如果我将鼠标悬停在#download上,fadeIn应该在1秒的延迟后开始。如果我同时将鼠标移出fadeIn不应启动。找我?延迟()或用stop()超时?

我真的不知道该怎么做,有什么想法?

+0

@ user239831 - 你对此有一个突出的问题吗? – 2010-11-12 13:03:26

回答

25

在这种情况下,您需要使用setTimeout(),因为.delay()的工作方式(以及您无法取消它)。

$('.file a').live('mouseenter', function() { 
    $.data(this, 'timer', setTimeout(function() { 
     $('#download').stop(true, true).fadeIn('fast'); 
    }, 1000)); 
}).live('mouseleave', function() { 
    clearTimeout($.data(this, 'timer')); 
    $('#download').stop(true, true).fadeOut('fast'); 
}); 

You can give it a try here

如果您使用.delay(),它将为元素取出下一个动画,无论您是否早先清除该队列。所以你需要一个暂停,你可以取消,这是通过手动呼叫setTimeout()并存储结果$.data(),以便您可以稍后通过clearTimeout()清除。

+2

+1简洁明了的解决方案。 – Tomalak 2010-07-25 12:37:45

+0

非常好。延迟是非常重要的。我仍然知道无法取消这意味着它应该非常小心地使用。这是解决这个问题的好方法。谢谢。 – Jake 2012-06-22 21:58:18

+0

嗨。我在[this jsFiddle](http://jsfiddle.net/GZV5V/84/)中为'slideDown()'和'slideUp()'尝试了相同的功能,但效果不佳。你能告诉我我在这里错过了什么吗?注意:我正在尝试不使用'hoverIntent()'函数。 – hims056 2013-11-13 05:24:39

3

使用setTimeout函数

$('.file a').live('mouseenter', function() { 
setTimeout(function(){ 
    $('#download').stop(true, true).fadeIn('fast'); 
}, 1000); 
}).live('mouseleave', function() { 
    $('#download').stop(true, true).fadeOut('fast'); 
}); 

的setTimeout指定毫秒后执行的函数内的代码(在本例1000)。

+1

你还需要存储/清除该超时,如果你快速悬停进出,它将在200ms内完成fadeOut()(如果它运行的话),然后800ms之后有一个排队的fadeIn,即使你'不要超过元素。看看这里看看我的意思:http://jsfiddle.net/nick_craver/T9t6N/要测试,快速悬停并离开链接。 – 2010-07-25 12:39:33

0

你可以在不使用延迟事件的情况下在jquery上使用它。

$('.file a').hover(function() { 
    time = setTimeout(function() { 
    $('#download').fadeIn(); 
    },1000); 
},function(){ 
    clearTimeout(time); 
}); 

1000是你的时间,它后$('#下载')将淡入。

4

我一直在寻找的答案类似的问题,我发现.animate()也可以用来处理这个问题,它服从.stop()

这将是这个样子:

$('.file a').live('mouseenter', function() { 
    $('#download') 
     .stop(true, true) 
     .animate({opacity:0}, 1000);   // one second delay 
     .animate({opacity:1}, 'fast', 'swing'); 
}).live('mouseleave', function() { 
    $('#download') 
     .stop(true, true) 
     .animate({opacity:0}, 'slow', 'swing'); 
});