本文分享如何為 jQuery 的滑鼠移入(hover)事件加上延時處理,具體 JS 程式碼如下:
(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);
hoverDelay 方法有兩個時間參數與兩個事件參數,意義如下:
hoverDuring 滑鼠移入的延時時間
outDuring 滑鼠移出的延時時間
hoverEvent 滑鼠移入後執行的方法
outEvent 滑鼠移出後執行的方法
這個方法的目的,是把「滑鼠移入事件」與「延時」分離開來,延時與清除延時的細節都由它處理好。你要做的,就是設定延時的長短,以及對應的移入或移出事件即可。舉個簡單的例子:
$("#test").hoverDelay({ hoverDuring: 1000, outDuring: 1000, hoverEvent: function(){ $("#tm").show(); }, outEvent: function(){ $("#tm").hide(); } });
以下是一個更簡潔的案例:
$("#test").hoverDelay({ hoverEvent: function(){ alert("經過 我!"); } });
它代表的含義是:id 為 test 的元素在滑鼠移入後 200 毫秒(預設 hoverDuring),彈出含有「經過 我!」字樣的提示框。這種延時技巧常用於避免使用者滑鼠一掃而過就觸發效果,讓互動更順滑自然。以上就是關於 jQuery 滑鼠移入事件延時處理的全部內容,希望對你的學習有所幫助。