javascript JS for navmenu点击切换,包括点击关闭

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript JS for navmenu点击切换,包括点击关闭相关的知识,希望对你有一定的参考价值。

// Note that this is specifically aimed at the header navmenu
(function() {
  // Toggle the open class on the dropdown menu when the menu toggle is clicked.
  let mainMenuToggles = document.querySelectorAll(".navmenu--header.navmenu--click-to-toggle span.navmenu__expand");

  for (var i = 0; i < mainMenuToggles.length; i++) {
    mainMenuToggles[i].addEventListener("click", handleMainMenuTogglesClicked);
  }

  function handleMainMenuTogglesClicked(event) {
    let toggle = event.toElement;
    let dropdownMenu = toggle.closest('.navmenu__menu-item--has-dropdown');
    dropdownMenu.classList.toggle("open");
  }

// Open the dropdown menu if the user clicks a closed menu link.
// Follow the link if the user clicks an open dropdown menu.
  let mainDropdownMenuLinks = document.querySelectorAll(
    ".navmenu--header.navmenu--click-to-toggle .navmenu__menu-item--has-dropdown > a"
  );

  for (var i = 0; i < mainDropdownMenuLinks.length; i++) {
    mainDropdownMenuLinks[i].addEventListener(
      "click",
      handleDropdownMenuClicked
    );
  }

  function handleDropdownMenuClicked(event) {
    let dropdownMenu = event.toElement.closest(".navmenu__menu-item--has-dropdown");

    if (!(dropdownMenu.classList.contains('open'))) {
      event.preventDefault();
      dropdownMenu.classList.add("open");
    }
  }

// Close the dropdown menu if the user clicks away.
  document.addEventListener("click", handleNonDropdownClicked);

  function handleNonDropdownClicked(event) {
    let openMenu = document.querySelector(".navmenu--header.navmenu--click-to-toggle .navmenu__menu-item--has-dropdown.open");

    if (openMenu == null) {
      return;
    } else {
      let targetElement = event.target;
      do {
        if (targetElement === openMenu) {
          return;
        }
        targetElement = targetElement.parentNode;
      } while (targetElement);

      event.preventDefault();
      openMenu.classList.remove("open");
    }
  }

})();

以上是关于javascript JS for navmenu点击切换,包括点击关闭的主要内容,如果未能解决你的问题,请参考以下文章

elementUI 的 navmenu 怎么在 v-for 中 循环不同的标签?

NavMenu 可以在 element-ui 中响应吗?

element-ui 之 NavMenu 的使用

element NavMenu组件实现

NavMenu 阻止事件冒泡

更新 MudBlazor 后,我的带有 NavMenu 的抽屉消失了