To achieve this functionality, you can use JavaScript to add and remove a class on the menu element based on user actions. Here's an example code snippet: \n\nHTML:\nhtml\n<button id="menu-btn">Open Menu</button>\n<ul id="menu" class="hide">\n <li>Option 1</li>\n <li>Option 2</li>\n <li>Option 3</li>\n</ul>\n\n\nCSS:\ncss\n.hide {\n display: none;\n}\n\n\nJavaScript:\njavascript\ndocument.addEventListener("DOMContentLoaded", function() {\n var menuBtn = document.getElementById("menu-btn");\n var menu = document.getElementById("menu");\n\n menuBtn.addEventListener("click", function(e) {\n e.stopPropagation(); // Prevents the click event from bubbling up to the document\n\n menu.classList.toggle("hide");\n });\n\n document.addEventListener("click", function() {\n menu.classList.add("hide");\n });\n\n menu.addEventListener("click", function(e) {\n e.stopPropagation(); // Prevents the click event from bubbling up to the document\n });\n});\n\n\nIn this code, we first select the menu button and the menu itself using their respective IDs. We then attach a "click" event listener to the menu button. When the button is clicked, the event listener function is executed. Inside the function, we use the toggle() method to add or remove the "hide" class from the menu element, which controls its visibility.\n\nNext, we attach a "click" event listener to the document itself. When the user clicks anywhere in the document, the event listener function is executed. Inside this function, we add the "hide" class to the menu element, effectively hiding it.\n\nFinally, we attach a "click" event listener to the menu element itself to prevent the click event from bubbling up to the document. This ensures that clicking inside the menu does not trigger the document's event listener and hide the menu.\n\nWith this code, when the user clicks the "Open Menu" button, the menu will appear. If the user clicks anywhere outside the menu, the menu will be hidden by adding the "hide" class.

How to Toggle Menu Visibility on Click: JavaScript Example

原文地址: https://www.cveoy.top/t/topic/qosw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录