如何在单击子菜单项时以编程方式关闭菜单?

问题描述 投票:0回答:1

正如标题所说,我无法真正关闭每个代码的菜单。

我的子菜单项是父元素的锚链接,例如

site#anchor

如果我在该页面上,我想在单击锚链接后关闭菜单。

我尝试了这种方法,但它无法正常工作

menu.querySelectorAll('.level_2 a').forEach(bindClick);
            
function bindClick(item){
  if (item.href.substring(item.href.lastIndexOf('/')).indexOf(pathname) >= 0){
    let hash = item.getAttribute("href");
                    
    item.addEventListener("click", () => {
      scroll({
    top: document.querySelector(hash).offsetTop - document.getElementById('header_bottom').clientHeight,
        behavior: "smooth"
      });
      api.close();
    });
  }
}    

菜单关闭,但菜单背景并没有消失。

我错过了什么?

mmenu
1个回答
0
投票

尝试下面的代码。

menu.querySelectorAll('.level_2 a').forEach(bindClick);

function bindClick(item) {
  if (item.href.substring(item.href.lastIndexOf('/')).indexOf(pathname) >= 0) {
    let hash = item.getAttribute("href");
    enter code here
    item.addEventListener("click", (event) => {
      event.preventDefault(); // Prevent the default link behavior

      scroll({
        top: document.querySelector(hash).offsetTop - document.getElementById('header_bottom').clientHeight,
        behavior: "smooth"
      });

      // Close the menu programmatically
      var menuElement = document.querySelector("#your-menu-selector"); // Replace with your menu selector
      // Close the menu using the appropriate method based on the menu library you're using
      // For example, if you're using the menulibrary, you can use:
      menuElement. menu.close();

      // If you're using a different menu library, refer to its documentation for the correct close method
    });
  }
}

注意:在此代码中,执行所需操作(在本例中为滚动)后,菜单将以编程方式关闭。您需要将“#your-menu-selector”替换为菜单元素的正确选择器。

以编程方式关闭菜单的具体方法取决于您使用的菜单库。该代码片段假设您正在使用菜单库。如果您使用不同的库,请务必参阅其文档,了解以编程方式关闭菜单的适当方法。

© www.soinside.com 2019 - 2024. All rights reserved.