简体   繁体   English

当我点击相同的菜单项(锚链接)时,汉堡菜单不会关闭

[英]Hamburger Menu won't close when I click on same menu item (anchor link)

I have a hamburger menu (navigation).我有一个汉堡菜单(导航)。 Every link jumps to a place on the same web site (anchor links).每个链接都跳转到同一网站上的某个位置(锚链接)。 The menu closes after a scroll event (so basically when I click on a link that triggers a scroll (jump) to the anchor)滚动事件后菜单关闭(所以基本上当我点击触发滚动(跳转)到锚点的链接时)

This is the script I use to trigger the closing of the menu.这是我用来触发菜单关闭的脚本。

<script type="text/javascript">
function hideMenu(){
  let menuOpen = document.querySelector('.menu-trigger').checked;

  if(menuOpen = true){
    document.querySelector('.menu-trigger').checked = false;
  }
  }
  window.addEventListener("scroll", hideMenu);
    </script>

This is what I have in my CSS file.这就是我的 CSS 文件中的内容。 The Menu links are anchor links (#contact)菜单链接是锚链接(#contact)

https://codepen.io/takaneichinose/pen/aNrBKp https://codepen.io/takaneichinose/pen/aNrBKp

After I jumped to the anchor and I try to click the same anchor link from the menu then the menu won't close (since there will be no scrolling event).在我跳转到锚点并尝试从菜单中单击相同的锚点链接之后,菜单不会关闭(因为不会有滚动事件)。

Is there another method to close the hamburger menu without using a scrolling event?是否有另一种方法可以在不使用滚动事件的情况下关闭汉堡菜单?

Not sure if it is what you're looking for, but you could just trigger the hideMenu() function when the a elements with an specific class (Add a class to all the anchors) are clicked.不确定它是否是您要查找的内容,但您可以在单击具有特定类的a元素(将类添加到所有锚点)时触发hideMenu()函数。 I would suggest using document.querySelectorAll('.className') to create an array that can be iterated with for or forEach() As an example: (I'm adding a class to the anchors named .nav-anchor )我建议使用document.querySelectorAll('.className')创建一个可以用forforEach()迭代的数组作为一个例子:(我正在向名为.nav-anchor的锚点添加一个类)

const navAnchors = document.querySelectorAll('.nav-anchor')
navAnchors.forEach(anchor =>{
  function handleMenu(){
    let menuOpen = document.querySelector('.menu-trigger').checked;

    if(menuOpen = true){
      document.querySelector('.menu-trigger').checked = false;
    }

  }
  anchor.addEventListener("click", handleMenu)

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM