jQuery:hover延時效果的一些處理

lblank發表於2016-12-05

一開始滑鼠的hover事件我都會用css:hover偽類來實現,它的特點也很明顯,就是無延時立即觸發,但有時可能會造成一些干擾,想要使用者體驗更好的話就要用js。
比如,讓滑鼠在元素上停留規定時間內才觸發hover事件。我在一篇博文上找到一段比較好的處理程式碼 :
文章出處

(function($){
    $.fn.hoverDelay = function(options){
        var defaults = {
            // 滑鼠經過的延時時間
            hoverDuring: 200,
            // 滑鼠移出的延時時間
            outDuring: 200,
            // 滑鼠經過執行的方法
            hoverEvent: function(){
                // 設定為空函式,繫結的時候由使用者定義
                $.noop();
            },
            // 滑鼠移出執行的方法
            outEvent: function(){
                $.noop();    
            }
        };
        var sets = $.extend(defaults,options || {});
        var hoverTimer, outTimer;
        return $(this).each(function(){
            $(this).hover(function(){
                // 清除定時器
                clearTimeout(outTimer);
                hoverTimer = setTimeout(sets.hoverEvent,
                    sets.hoverDuring);
                }, function(){
                    clearTimeout(hoverTimer);
                    outTimer = setTimeout(sets.outEvent,
                        sets.outDuring);
                });    
            });
    }      
})(jQuery);
    
// 具體使用,給id為“#test”的元素新增hoverEvent事件
$("#test").hoverDelay({
    // 自定義,outEvent同
    hoverEvent: function(){
        alert("經過我!");
    }
});

這段程式碼好在於把滑鼠經過事件和延時分離出來,延時以及延遲的清除都交由hoverDelay來處理,具體hover事件自己自定,是一段能夠很通用的程式碼。
但運用起來還有些小問題,在自定義hoverEvent、outEvent中使用this的話,它所指向的是window這個物件,而不是當前上下文,所以我改進了下,通過apply()來實現this繫結。
改進部分:

return $(this).each(function(){
        // 儲存當前上下文的this物件
        var $this = $(this)
        $this.hover(function(){
            clearTimeout(outTimer);
            hoverTimer = setTimeout(function () {
                // 呼叫替換
                sets.hoverEvent.apply($this);
            }, sets.hoverDuring);
        }, function(){
            clearTimeout(hoverTimer);
            outTimer = setTimeout(function () {
                sets.outEvent.apply($this);
            }, sets.outDuring);
        });
    });

改完以後我自己的小專案都用這個方法來處理hover或者其他的延時效果了。

相關文章