开发者

Adding MouseOut delay to this piece of jQuery (menu nav)

开发者 https://www.devze.com 2023-01-14 02:47 出处:网络
I\'m a complete absolute jQuery noob. I\'ve been following a tutorial to add a CSS/jQuery navigation menu to my site, and I got it working.. The only thing I would like to see added is a small delay o

I'm a complete absolute jQuery noob. I've been following a tutorial to add a CSS/jQuery navigation menu to my site, and I got it working.. The only thing I would like to see added is a small delay on Mouse out, because the dropdown menu is disappearing instantly when you mouse out which makes the menu a bit annoying to use. Here's my script:

function mainmenu(){
$(" .top-menu ul ").css({display: "none"}); // Opera Fix
$(" .top-menu li").hover(function(){
  $(this).find('ul:first').css({visibility: "visible",display: "none"}).show(400);
  },function(){
  $(this).find('ul:first').css({visibility: "hidden"});
  });
}

 $(document).ready(function(){
 mainmenu(开发者_JAVA百科);
});

Would anyone be so kind to add the needed code to this script. I'll promise to study how you've done it, so I actually learn from it ;-D


You could do something like this, giving it a 500ms delay:

function mainmenu(){
  $(".top-menu ul ").hide();
  $(".top-menu li").hover(function() {
    clearTimeout($.data(this, 'timeout'));
    $(this).find('ul:first').show(400);
  }, function() {
    $.data(this, 'timeout', setTimeout($.proxy(function() { 
       $(this).find('ul:first').hide();
    }, this), 500));
  });
}
$(mainmenu);

This adds a 500 ms delay via setTimeout() and just stores the timer id with the element using $.data(), when hovering back in the element, it'll clear the timeout and won't run it again until you over out...so you have to be off the element for 500ms for it to hide.

Or, do something very similar with the hoverIntent plugin which is for just this problem.


$(" .top-menu li").hover(function(){
    $(this).find('ul:first').css({visibility: "visible",display: "none"}).show(400);
},function(){

    // Note here...
    setTimeout(function(){
        $(this).find('ul:first').css({visibility: "hidden"});
    }, 2000);
    // 2000 is a delay time in milliseconds, change it

});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号