jquery hover and setTimeout / clearTimeOut

99封情书 提交于 2019-12-18 12:07:27

问题


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

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.

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.

Here is my code :

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

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

回答1:


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();
        }
    );
}



回答2:


var timer is a local variable.
It doesn't exist outside that handler.

You need to make it a global variable.




回答3:


Here is how I would do it

var timer
$("#mylink").mouseenter(function(){clearTimeout(timer);$('#submenu').show()})
$("#mylink").mouseout(function(){timer = setTimeout(function(){$('#submenu').hide();}, 1000);})



回答4:


If you put #submenu inside of #mylink you won't need a second event handler for #submenu and you would have something like this:

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

By the way, you don't need jQuery for this. In plain js won't be so long to code.



来源:https://stackoverflow.com/questions/10299531/jquery-hover-and-settimeout-cleartimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!