jquery hover 延迟运行插件
说到延时,离不开window下的setTimeout方法,本实例的jQuery方法的核心也是setTimeout。代码不长,完整如下:
(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);
这段代码的目的在于让鼠标经过事件和延时分离的出来,延时以及延迟的清除都已经由此方法解决了。您所要做的,就是设定延时的时间大小,以及相应的鼠标经过或是移除事件即可。举个简单的例子吧,如下代码:
$("#test").hoverDelay({
hoverEvent: function(){
alert("经过我!");
}
});
表示的含义是id为test的元素在鼠标经过后200毫秒后弹出含有“经过我!”文字字样的弹出框。