求助:如何实现导航栏图标先右移再上移的分步动画效果
Hey there! I see the issue with your navbar icon animations firing at the same time—let's break down why that's happening and get it sorted out.
What's Going Wrong in Your Current Code
Your use of $.when(x.css("margin-left")=="50%") doesn't work the way you might expect:
$.when()expects Deferred/Promise objects to wait on, but you're passing a boolean value (trueorfalse). This means thedone()callback runs immediately, triggeringnavbar2()right afternavbar()instead of waiting for the margin-left change to finish.- Even if your element has a CSS transition, checking
css("margin-left")directly is unreliable—browsers might return pixel values instead of percentages during the transition, and the check happens synchronously before the animation completes.
Solution 1: Use CSS transitionend Event (Best for CSS-Based Animations)
If you're using CSS transitions for smooth animations (the recommended approach for performance), listen for the transitionend event to trigger the second animation only after the first finishes.
First, make sure your icon has a CSS transition defined:
#a { /* Adjust the transition duration to match your desired speed */ transition: margin 0.3s ease; }
Then update your JavaScript code:
function navbar() { const navIcon = document.getElementById("a"); navIcon.style.marginLeft = "50%"; // Define a one-time listener for the transition end event const handleTransitionEnd = (event) => { // Ensure we're reacting to the margin-left transition specifically if (event.propertyName === "margin-left") { navIcon.removeEventListener("transitionend", handleTransitionEnd); navbar2(); // Trigger the second animation now } }; navIcon.addEventListener("transitionend", handleTransitionEnd); } function navbar2() { document.getElementById("a").style.marginTop = "-100px"; } $(document).ready(function(){ $("#a").click(function(){ navbar(); }); });
Solution 2: Use jQuery's Animate Callback (For jQuery-Based Animations)
If you prefer using jQuery's animate() method instead of CSS transitions, you can use the built-in callback function that runs when the first animation completes:
function navbar() { $("#a").animate({ marginLeft: "50%" }, 300, function() { // This callback runs only after the margin-left animation finishes navbar2(); }); } function navbar2() { $("#a").animate({ marginTop: "-100px" }, 300); } $(document).ready(function(){ $("#a").click(function(){ navbar(); }); });
Key Notes
- For most cases, Solution 1 is better—CSS transitions are smoother and more performant than JavaScript animations.
- Always remove event listeners after they fire (like we did in Solution 1) to prevent unexpected repeated triggers if the icon is clicked again before animations finish.
Hope this gets your menu bar animations working exactly how you want them! Let me know if you need further tweaks.
内容的提问来源于stack exchange,提问作者İ. ALP EREN GÜL

