延迟鼠标输入事件,如果鼠标在元素内引发事件

delay mouseenter event and raise event if mouse inside the element

本文关键字:鼠标 事件 元素 如果 输入 入事件 延迟      更新时间:2023-09-26

我使用基于jQuery开发的选项卡视图:

https://d2o0t5hpnwv4c1.cloudfront.net/001_Tabbed/site/jQuery.html#

我更改了选项卡通过mouseenter事件更改的代码。 我想延迟mouseenter事件的执行,因此如果鼠标进入 elemnt 并在那里停留了一段时间mouseenter执行其他(如果鼠标在时间少于该部分时间)mouseenter不会执行。我写了这段代码:

$(document).ready(function () {
        $('a.tab').on('mouseenter', function () {
            var thisElement = $(this);
            setTimeout(function () {
                $(".active").removeClass("active");
                thisElement.addClass("active");
                $(".content").slideUp();
                var content_show = thisElement.attr("title");
                $("#" + content_show).slideDown();
            }, 300);
        });
    }); 

但是如果我把鼠标从元素中拿出来mouseenter就会超过。如何解决这个问题?

谢谢

您需要

存储超时句柄并在mouseleave上取消它:

var timeout; 
$(document).ready(function () {
    $('a.tab').on('mouseenter', function () {
        var thisElement = $(this);
        if (timeout != null) { clearTimeout(timeout); }
        timeout = setTimeout(function () {
            $(".active").removeClass("active");
            thisElement.addClass("active");
            $(".content").slideUp();
            var content_show = thisElement.attr("title");
            $("#" + content_show).slideDown();
        }, 300);
    });
    $('a.tab').on('mouseleave', function () {
        if (timeout != null) { 
           clearTimeout(timeout); 
           timeout = null;
        }
    });
});