JS新手求助:如何用同一按钮实现汉堡菜单的开关功能?
Hey there! I see you're just starting out with JavaScript and ran into a common snag with your toggleable burger menu. Let's get this sorted so your button can both open and close the sidebar, and we can ditch that temporary close button at the bottom.
The Root of the Issue
Right now, your button's onclick always calls openSlideMenu()—even after the icon switches to an X. That's why clicking it again doesn't close the menu; it's still trying to open it! The myFunction() is toggling the button's class, but we haven't linked that class change to the menu's visibility logic yet.
Step-by-Step Solution
Let's create a single, unified function that handles both the button's animation and the menu's show/hide behavior:
Update the button's onclick handler
Replace the two separate function calls in your burger menu div with one toggle function:<div class="burger-menu-btn" onclick="toggleSlideMenu(this)"> <div class="burger-menu-bar-1"></div> <div class="burger-menu-bar-2"></div> <div class="burger-menu-bar-3"></div> </div>Replace your existing JavaScript functions
RemovemyFunction(),openSlideMenu(), andcloseSlideMenu(), then add this combined function:function toggleSlideMenu(x) { // Toggle the button's class to switch between burger icon and X x.classList.toggle("change"); // Grab the sidebar element const sidebar = document.getElementById('burger-menu'); // Check if the sidebar is currently open if (sidebar.style.width === '100%') { // Close it if open sidebar.style.width = '0px'; } else { // Open it if closed sidebar.style.width = '100%'; } }Remove the temporary close button
Delete this line from your sidebar div—we don't need it anymore:<a href="#" class="btn-close" onclick="closeSlideMenu()">×</a>
How It Works Now
Every time you click the button:
- The function first switches the button's class between
burger-menu-btnandburger-menu-btn change, triggering the animation between the burger icon and X. - It then checks the sidebar's current width. If it's open (
100%), it shrinks it to0pxto close it. If it's closed, it expands it to100%to open it.
This way, the same button handles both opening and closing the menu, just like you wanted!
内容的提问来源于stack exchange,提问作者Søren Nordensgaard

