2010-11-14 92 views
1

我想在运行更多代码之前在.hover()回调函数中添加一个小延迟。我还需要停止计时器,如果它存在,当您悬停另一个触发相同的.hover()函数的元素。 我目前有它的工作,但它不漂亮,我分配一个计时器到全球,并确保有一个更好的方式来做到这一点。在调用函数之前在.hover()回调函数中添加一个延迟

以下是我有:

PACKAGES.activity_icons.hover(function() { 

    // If a timer exists kill it here becuase we don't want the 
    // functions in the timer called if we are hovering on another icon 
    if(typeof image_restore_timer != 'undefined') 
    { 
    clearTimeout(image_restore_timer); 
    } 

    // Only swap image if icon has a class 
    if($(this).attr('class') !== '') 
    { 
    $(this).closest('.package').find('.left_wrap > img').hide(); 
    // Show the image with the same class as the icon we hovered 
    $(this).closest('.package').find('.left_wrap img.'+$(this).attr('class')).show(); 
    } 

}, function() { 

    var this_ref = $(this); 

    // Store timer in a global and restore images after a pause 
    image_restore_timer = setTimeout(function() { 
    (function(el) { 
    el.closest('.package').find('.left_wrap img.'+this_ref.attr('class')).hide(); 
    el.closest('.package').find('.left_wrap > img:eq(0)').fadeIn('slow'); 
    })(this_ref) 
    }, 1000); 

}); 

回答

3

可以使用$.data()存储每个元素(而不是全球性的)的定时器,像这样:

PACKAGES.activity_icons.hover(function() { 
    clearTimeout($.data(this, 'timer')); 

    if(this.className === '') return; 
    $(this).closest('.package').find('.left_wrap > img').hide() 
         .end().find('.left_wrap img.'+ this.className).show(); 
}, function() { 
    var el = this; 
    $.data(this, 'timer', setTimeout(function() { 
    $(el).closest('.package').find('.left_wrap img.' + el.className).hide() 
         .end().find('.left_wrap > img:eq(0)').fadeIn('slow'); 
    }, 1000)); 
}); 

的其他变化都只是一些优化,主要想法是使用$.data()存储定时器并清除相同的定时器。另外,clearTimeout()对于空或已经运行的定时器没有错误,所以你可以直接调用它而不进行检查。

+0

太棒了!谢谢 – davewilly 2010-11-14 00:12:07

+0

@davewilly - 欢迎! – 2010-11-14 00:14:52

2

您正在寻找hoverIntent插件。

+0

谢谢,在发布问题之前,我确实研究了解决方案,并得出结论hoverIntent插件对于我需要做的事情并不适用。 – davewilly 2010-11-14 00:37:35