hover延迟执行

网页的导航经常会用到hover事件,例如:hover改变背景色,hover下拉显示二级菜单等。

如果每当鼠标快速或是不小心划过导航就执行hover之后的事件,会出现一种不好的体验(找不到形容词,就是怪怪的)。

所以为了用户体验,一般会给导航的hover加上一定的延迟。达到避免用户频繁快速或是不小心滑过导航出现的不好体验。

这里提供hover延迟的方法:

1、定义变量

    var _is_unhover = false;
    $(".nav").hover(function () {
        var _this = $(this);
        _is_unhover = false;
        setTimeout(function () {
            if (_is_unhover) return;
            _this.find('ul').show();//do something
        }, 200);
    }, function () {
        _is_unhover = true;
        $(this).find('ul').hide();//do something
    })

2、判断状态

$(".nav").bind('mouseenter focusin', function () {
        $(".nav").data('mouseenter', 1);
     var _this = $(this); setTimeout(
function () { if ($(".nav").data('mouseenter') == 0) return; _this.find('ul').show();//do something }, 100); }); $(".nav").bind('mouseleave focusout', function () { $(".nav").data('mouseenter', 0); setTimeout(function () { if ($(".nav").data('mouseenter') == 1) return; _this.find('ul').hide();//do something }, 100); });
与尘埃中开出花朵。
原文地址:https://www.cnblogs.com/congfeicong/p/7455283.html