2010-11-14 94 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