Adding MouseOut delay to this piece of jQuery (menu nav)
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
});
精彩评论