为悬停功能添加延迟

时间:2010-12-15 16:39:38

标签: jquery

我有这个代码可以触发一个大型菜单。

    $('li#locations a').hover(function(){
$('#locationsSuperNav').slideDown();
}); 

$('#locationsSuperNav').mouseleave(function(){
$(this).slideUp();
});

这是html

<div id="nav">
<ul id="nav_509815">
<li><a href="/Culture/cultureHome">Culture</a></li>
<li><a href="/Advantage/advantageHome">Advantage</a></li>
<li><a href="/Testimonials/parentstories">Testimonials</a></li>
<li><a href="/Programs/programs">Programs</a></li>
<li class="locations" id="locations"><a href="/Locations/locationsHome">Locations</a></li>
<li><a href="/Careers/careers">Careers</a></li>
</ul>
<div id="locationsSuperNav" class="" style="display: none;">All the content goes here</div>
</div>

我想做的是为原始悬停事件添加一个简单的计时器。这样,如果用户不小心碰到了标签,除非他们坐在那里半秒左右,否则它不会开火。有什么建议??

2 个答案:

答案 0 :(得分:1)

你应该看一下使用jQuery的delay() function

更新(请参阅编辑历史记录)

好的。现在我更好地了解你的问题。谢谢你的澄清。我认为这段代码可以满足您的需求。您可以在此处播放示例:http://jsfiddle.net/57eGD/

$('li#locations a').mouseenter(function() {
    var curElement = this;
    var timeoutId = setTimeout(function() {
       $('#locationsSuperNav').slideDown();
    }, 650);

    // Use data so trigger can be cleared.
    $(curElement).data('timeoutId', timeoutId);
}).mouseleave(function() {
    clearTimeout($(this).data('timeoutId'));
});

$('#locationsSuperNav').mouseleave(function() {
    $(this).slideUp();
});

基本上,delay()对你不起作用,因为它只会延迟事件,但它不允许取消事件。因此,它不适合您,因为即使您延迟slideDown()事件,如果用户将鼠标移除,它仍然会发生。因此,您必须使用允许取消的window.setTimeout。但是,(某种)棘手的部分是你必须能够告诉超时取消。这就是jQuery的data function发挥作用的地方。此功能允许您将任何类型的数据附加到DOM元素。因此,在您的情况下,您应该将它附加到您关心触发事件的元素(在本例中为$('li#locations a')),如果您在事件触发之前离开元素,则允许您取消它。您可以将650调整为更长或更短的延迟。

另外需要注意的是,hover()应该在这里工作,而不是mouseenter和mouseleave。它应该是这样的:

$('li#locations a').hover(function() {
    var curElement = this;
    var timeoutId = setTimeout(function() {
       $('#locationsSuperNav').slideDown();
    }, 650);

    // Use data so trigger can be cleared.
    $(curElement).data('timeoutId', timeoutId);
}, function() {
    clearTimeout($(this).data('timeoutId'));
});

我希望这会对你有所帮助!对我来说也是很好的学习经历。

答案 1 :(得分:0)

jquery.hoverIntent.js正是您所寻找的。

http://plugins.jquery.com/project/hoverIntent

相关问题