单击隐藏中的链接时关闭移动菜单 [英] Close mobile menu when clicking link in hid
问题描述
我的网站上有一个移动菜单,按下按钮时会显示该菜单.当我使用以下代码按下此按钮时,显示和隐藏菜单的效果非常好:
I have a mobilemenu on my website that is shown when pressing a button. Showing and hiding the menu works perfectly when I press this button with the code below:
但我也想在单击此菜单中的链接时隐藏菜单.我怎样才能做到这一点?
But I also want to hide the menu when I click on a link in this menu. How can I manage to do this?
var coll = document.getElementsByClassName("hamburger");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var mobilemenuspace = this.nextElementSibling;
if (mobilemenuspace.style.display === "block") {
mobilemenuspace.style.display = "none";
} else {
mobilemenuspace.style.display = "block";
}
});
}
推荐答案
向每个链接添加事件侦听器.代码可能如下所示.
Add event listeners to each of the links. The code could look something like the following.
请注意,对我来说,下面的代码很麻烦,而且在不明确或不安全的地方,这很好,这是一个好的开始.jQuery 可以让事情变得更好一点,但在 React 或 Vue 中会更整洁.
Note, to me, the code below is cumbersome and at places unclear or unsafe, which is fine, it's a good start. jQuery can make things a little better, but it would be neater in React or Vue.
const toggleMenu = () => {
const menu = document.getElementsByClassName("the-list")[0];
if (typeof menu === "undefined" || typeof menu === "null") {
throw new Error("menu element not found");
};
const isHidden = menu.classList.contains("hidden");
if (isHidden) {
menu.classList.remove("hidden");
} else {
menu.classList.add("hidden");
};
};
const button = document.getElementById("the-button");
button.addEventListener("click", toggleMenu);
const links = document.getElementsByClassName("a-link");
for (link of links) {
link.addEventListener("click", toggleMenu);
};
.hidden {
display: none;
}
<ul class="the-list hidden">
<li class="a-link"><a href="#">link 1</a></li>
<li class="a-link"><a href="#">link 2</a></li>
</ul>
<button id="the-button">toggle menu</button>
这篇关于单击隐藏中的链接时关闭移动菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!