jquery 悬停和 setTimeout/clearTimeOutjquery、setTimeout、clearTimeOut

2023-09-07 22:19:34 作者:雨落倾城夏未凉

我目前正在尝试使用子菜单制作菜单.这就是我想做的事情.

I'm currently trying to do a menu with submenu. Here is what i want to do.

悬停链接(#mylink)时,我想在其下方显示一个 div(我们称之为#submenu").鼠标离开此链接,希望在 5 秒后执行一个功能.

On hover a link (#mylink) i want to display a div (lets call it "#submenu") right under it. On mouse leave this link a want to execute a function after 5 second.

在这 5 秒的时间间隔内,如果我将鼠标悬停在我的 div (#submenu) 上,我想清除超时.所以这个 div 不会在 5 秒后消失.

In this interval of 5 seconds, if i hover my div (#submenu) i want to clearTimeout. So this div won't desapear after 5 seconds.

这是我的代码:

$(document).ready(function()
{
    $("#mylink").hover(
        function ()
        {
            $('#submenu').show();
        },
        function()
        {
            var timer = setTimeout(function(){$('#submenu').hide();}, 5000);
        }
    );

    $("#submenu").hover(
        function ()
        {
            clearTimeout(timer);
        },
        function()
        {
            $('#submenu').show();
        }
    );
}

推荐答案

SLaks 有正确的答案,但要详细说明,您可以将 var timer 放在函数处理程序之外.请注意,此示例并未使 timer 成为全局变量 - 它只是扩大了其范围,以便所有处理程序都可以使用它.

SLaks has the right answer, but to elaborate on it, you would put var timer outside the function handler. Note that this example doesn't make timer a global variable - it just widens its scope so all handlers can use it.

$(document).ready(function(){
    var timer;
    $("#mylink").hover(
        function(){
            $('#submenu').show();
        }, function(){
            timer = setTimeout(function(){$('#submenu').hide();}, 5000);
        }
    );

    $("#submenu").hover(
        function(){
            clearTimeout(timer);
        }, function(){
            $('#submenu').show();
        }
    );
}