单击链接时关闭菜单

我有一个画布外菜单,当单击切换按钮时该菜单会飞出 - 到目前为止一切顺利。所有菜单链接共享相同的类名(在本例中为 .nav-link)。我需要在单击任何链接时关闭菜单,我认为已经选择了所有链接,并且我认为我必须循环遍历选择的数组,但我不确定是否实现它。现在,单击链接时不会发生任何事情。


我的HTML:


<ul class="nav-list">

   <li class="nav-item"><a href="#" class="nav-link">articles</a></li>

   <li class="nav-item"><a href="#" class="nav-link">tags</a></li>

   <li class="nav-item"><a href="#" class="nav-link">links</a></li>

   <li class="nav-item"><a href="#" class="nav-link">archive</a></li>

</ul>


我的CSS:


.nav-list {

    margin: 0;

    margin-top: 3.2em;

    padding: 0;

    background: #777;

    width: 100%;

    transform: translateX(-100%);

    transition: transform 300ms cubic-bezier(.5, 0, .5, 1);

}

我的JS:


const navToggle = document.querySelector('.nav-toggle')

const navLink = document.querySelectorAll('.nav-link')


navToggle.addEventListener('click', () => {

    document.body.classList.toggle('nav-open')

})


navLink.addEventListener('click', () => {

    document.body.classList.remove('nav-open')

})


开心每一天1111
浏览 93回答 2
2回答

函数式编程

您正在尝试将事件侦听器添加到节点集合(querySelectorAll for.nav-link与querySelectorfor .nav-toggle)。您可以迭代集合并将click事件侦听器添加到每个项目,或者仅侦听 s 的父元素.nav-link:const navToggle = document.querySelector('.nav-toggle')// replace this with something more sensibleconst navLinkParent = document.querySelector('.nav-link').parentElement;navToggle.addEventListener('click', () => {&nbsp; &nbsp; document.body.classList.toggle('nav-open')})// this is adding a click listener to ONE elementnavLinkParent.addEventListener('click', (event) => {&nbsp; // check if the clicked element matches what you're after&nbsp; if (event.target.classList.contains('nav-link')) {&nbsp; &nbsp; document.body.classList.remove('nav-open')&nbsp; }})

白猪掌柜的

您必须使用循环,因为querySelectorAll返回一个数组。const navToggle = document.querySelector('.nav-toggle')const navLink = document.querySelectorAll('.nav-link')navToggle.addEventListener('click', () => {&nbsp; &nbsp; document.body.classList.toggle('nav-open')})for (var i = 0; i < navLink.length; ++i) {&nbsp; &nbsp; navLink[i].addEventListener('click', () => {&nbsp; &nbsp; &nbsp; if(navToggle.classList.contains('nav-toggle')){&nbsp; &nbsp; &nbsp; &nbsp; (navToggle.classList.remove('nav-toggle');&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5