[英]JavaScript nav menu doesn't close when item, other than the first, is clicked
So I've got this JS mobile nav menu. 所以我有了这个JS移动导航菜单。 When the menu button is clicked the menu opens, and can then be closed by pressing the menu button again.
单击菜单按钮后,菜单将打开,然后可以再次按菜单按钮将其关闭。 I also want the menu to close when one of the nav items is clicked.
我也希望单击导航项之一时关闭菜单。 With the code below, I managed to make the menu close when the first item is clicked but for reasons unknown to myself it doesn't work for the other three nav items.
使用下面的代码,当单击第一个项目时,我设法使菜单关闭,但是由于我自己不知道的原因,它对其他三个导航项目均无效。 Has it maybe got something to do with the way I'm selecting the
nav-item
class? 可能与我选择
nav-item
类的方式有关吗? Also, my Javascript knowledge is very limited so there might be something obvious I'm missing. 另外,我的Javascript知识非常有限,因此可能缺少一些明显的东西。
HTML 的HTML
<nav class="main-nav">
<a href="#" class="nav-menu"><i class="fa fa-bars" aria-hidden="true"></i></a>
<div class="sidebar is-hidden">
<ul>
<li><a class="nav-item page-scroll" href="#about">ABOUT</a></li>
<li><a class="nav-item page-scroll" href="#framing">FRAMING</a></li>
<li><a class="nav-item page-scroll" href="#gallery">GALLERY</a></li>
<li><a class="nav-item page-scroll" href="#contact">CONTACT</a></li>
</ul>
</div>
</nav>
JS JS
const button = document.querySelector('.nav-menu')
const sidebar = document.querySelector('.sidebar')
const item = document.querySelector('.nav-item')
button.addEventListener('click', function (e) {
e.preventDefault();
sidebar.classList.toggle('is-hidden')
});
item.addEventListener('click', function () {
sidebar.classList.toggle('is-hidden')
});
Method document.querySelector
returns first found element. 方法
document.querySelector
返回找到的第一个元素。 If you want to add event listener to more than one element, you should use document.querySelectorAll
method instead. 如果要将事件侦听器添加到多个元素,则应改用
document.querySelectorAll
方法。 You will receive a list of elements. 您将收到一个元素列表。 You want to add event listener to each of them.
您想向每个事件监听器添加事件监听器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.