jQuery each()第二次点击无效果问题求助
Hey Rui, let's figure out why your close animation isn't working! The main issue here is how you're handling the positioning properties for your menu items, plus a couple of small tweaks to make the animations more reliable.
What's Going Wrong?
- Conflicting Positioning Properties: When you open the menu, you animate
left: '+=200'on.menu-item, but when closing, you animateright: '+=200'. These two properties fight each other—your elements don't know whether to respectleftorright, so the close animation doesn't produce any visible change. - Uncleared Animation Queues: If someone clicks the buttons quickly, old animations can pile up in the queue, which might prevent new ones from running as expected.
- Opacity Syntax: Using
opacity: "show"/"hide"is a bit outdated; using explicit values (1for visible,0for hidden) is more reliable with jQuery's.animate().
Fixed Code
Here's the adjusted JavaScript with explanations of the changes:
/* Menu Hamburguer Toggle */ jQuery('#fechado').click(function() { jQuery('#aberto').fadeIn(); jQuery('#fechado').fadeOut(); // Animate main navigation with explicit opacity value jQuery('.main-navigation').stop(true, true).animate({ right: "50%", opacity: 1 }, 500 ); // Animate menu items: slide in from left (assuming initial left is -200px) var delay = 0; jQuery('.menu-item:lt(16)').each(function(){ // Clear existing animations before starting new ones jQuery(this).stop(true, true).delay(delay).animate({ left: '+=200' // Slide to the right by 200px }, 500); delay += 100; }); return false; }); jQuery('#aberto').click(function() { jQuery('#aberto').fadeOut(); jQuery('#fechado').fadeIn(); // Animate main navigation back with opacity 0 jQuery('.main-navigation').stop(true, true).animate({ left: "0%", opacity: 0 }, 500 ); // Animate menu items: slide back to original position (left -=200) var delay = 0; jQuery('.menu-item:lt(16)').each(function(){ jQuery(this).stop(true, true).delay(delay).animate({ left: '-=200' // Slide back left by 200px to reset position }, 500); delay += 100; }); return false; });
Key Changes Made:
- Consistent Positioning: Now both open and close animations use the
leftproperty—opening adds 200px, closing subtracts 200px. This keeps the element's position logic clear. - Animation Queue Cleanup: Added
.stop(true, true)before each.animate()call. The firsttrueclears the animation queue, and the secondtruejumps to the end of any ongoing animation, so new animations start immediately. - Explicit Opacity Values: Replaced
"show"/"hide"with1and0for more predictable behavior. - Initial Position Note: I'm assuming your
.menu-itemelements start withleft: -200px(or similar) in your CSS. If that's not the case, adjust theleftvalues to match your initial styling (e.g., if they start atleft: 0, animate toleft: -200on close and back to0on open).
内容的提问来源于stack exchange,提问作者Rui Leming
相关产品推荐
相关产品推荐

