jQuery menu effect gone wrong
I am seeking for a way to fade a submenu in a list-ordered navigation as I want it to fade:
There is always an active menu item - and if the active menu item is in the submenu - also an active menu parent. So, at init the submenu with an active current item or current parent item should be visible. If I hover an other menu ite开发者_StackOverflow中文版m, its submenu will fade in, the active one fades out. After leaving the whole menu, the active submenu fades in again. Plus, I used the jQuery plugin hoverIntent (http://cherne.net/brian/resources/jquery.hoverIntent.html) to give a timeout for each hover action. This is what I got so far, but it's really buggy. For some reasons, submenus are sometimes just disappearing completely, also when hovering two items without leaving the navigation, two submenus overlap. Does anyone have an idea or tip for me? =) Please see a demo HERE: http://jsfiddle.net/BQuPz/
Problems with CSS: It's best not to play with display:none
and opacity
yourself, leave it up to jQuery and use the proper functions for fadeIn()
and fadeOut()
.
Instead of putting display:block; float:left;
on the menu's <li>
elements, you should use display:inline-block
. If you float the <li>
s, that effectively tears them out of their parent container, leaving the ul with zero size, hence it is impossible to listen to mouseleave
events unless you explicitly set its size.
Problems with code: In the hoverIntent plugin, timeout
might not be what you're looking for. Timeout automatically fires the out
event after a certain amount of time. To delay the hover effect, use sensitivity
and interval
instead. Check out the documentation page.
If you apply the above fixes, the only events needed are hoverIntent's over and the main navigation's mouseleave. The over
event fades in the current submenu and fades out the rest, the mouseleave
fades in the active submenu when the user hovers off the navigation. Look at your modified jsfiddle demo: http://jsfiddle.net/BQuPz/4/
// Hide inactive ones
$('#main-nav > li:not(.current-menu-parent) .sub-menu').hide();
// What to do when hovering over a menu item
$("#main-nav > li").hoverIntent({
over: function(){
// Find the hovered menu's sub-menu
var $submenu = $(this).find('.sub-menu');
// Stop the animation and fade out the other submenus
$('.sub-menu').not($submenu).stop(true,true).fadeOut(260);
// Fade in the current one
$submenu.fadeIn(260);
}
});
// What to do when user leaves the navigation area
$('#main-nav').mouseleave(function(){
// Fade out all inactive submenus
$('#main-nav > li:not(.current-menu-parent) .sub-menu').fadeOut(260);
// Fade in the active one
$('.current-menu-parent .sub-menu').fadeIn(260);
});
Instead of using animate in $(this).find("ul").animate({'opacity': '1'}, 250);
I would have used fadeIn and fadeOut functions with callbacks. Then you're sure your fadeIn animation begins after the fadeout ends
element.fadeOut(250,function(){otherElement.fadeIn(250)})
精彩评论