This code snippet demonstrates how to create a menu that opens when a button is clicked and closes when clicking outside the menu using JavaScript.

HTML:

<button id='open-menu'>Open Menu</button>
<div id='menu' class='menu'>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>
</div>

CSS:

.menu {
  display: none;
}

.menu.open {
  display: block;
}

JavaScript:

document.addEventListener('click', function(event) {
  var menu = document.getElementById('menu');
  var openMenuBtn = document.getElementById('open-menu');

  if (event.target === openMenuBtn) {
    menu.classList.toggle('open');
  } else if (!menu.contains(event.target)) {
    menu.classList.remove('open');
  }
});

In this example, when the 'Open Menu' button is clicked, it toggles the 'open' class on the menu element, which will display or hide the menu based on the CSS styles. If a click event occurs outside the menu (i.e., not within any element inside the menu), the 'open' class is removed from the menu element, hiding the menu.

JavaScript Menu Toggle: Open on Click, Close on Outside Click

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

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