jQuery – 鼠标经过(hover)事件的延时处理

一、关于鼠标hover事件及延时

鼠标经过事件为web页面上非常常见的事件之一。简单的hover可以用CSS :hover伪类实现,复杂点的用js。

一般情况下,我们是不对鼠标hover事件进行延时处理。但是,有时候,为了避免不必要的干扰,常会对鼠标hover事件进行延时处理。所谓干扰,就是当用户鼠标不经意划过摸个链接,选项卡,或是其他区域时,本没有显示隐藏层,或是选项卡切换,但是由于这些元素上绑定了hover事件(或是mouseover事件),且无延时,这些时间就会立即触发,反而会对用户进行干扰。

二、代码与实现【1】

说到延时,离不开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毫秒后弹出含有“经过我!”文字字样的弹出框。

三、代码与实现【2】

如果鼠标经过事件不会多次调用,可直接使用以下代码:

$(function(){
    var hoverTimer, outTimer;
    $(".mm-navbar").hover(function(){
        clearTimeout(outTimer);
        hoverTimer = window.setTimeout(function(){
            alert("经过我!");
        },200);
    },function(){
        clearTimeout(hoverTimer);
        outTimer = window.setTimeout(function(){
            alert("离开我!");
        },200);
    });
});

 

posted @ 2016-08-19 10:29  秋月白  阅读(5563)  评论(0编辑  收藏  举报