jquery hover and setTimeout / clearTimeOut

后端 未结 4 1908
北海茫月
北海茫月 2020-12-29 16:56

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

相关标签:
4条回答
  • 2020-12-29 17:22

    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);})
    
    0 讨论(0)
  • 2020-12-29 17:31

    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.

    0 讨论(0)
  • 2020-12-29 17:36

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

    You need to make it a global variable.

    0 讨论(0)
  • 2020-12-29 17:43

    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();
            }
        );
    }
    
    0 讨论(0)
提交回复
热议问题