很长一段时间以来,我一直在我的网站上使用汉堡菜单,这是一个具有绝对定位的全屏导航覆盖层,其中导航打开是(css)高度= 100%并且关闭=“0%”。它基于本教程:https://www.w3schools.com/howto/howto_js_fullscreen_overlay.asp
如果我使用 DIV 作为链接的容器,它工作得很好:打开/关闭按钮工作得很好, anchor 链接在单击时会自动关闭。一切都很好。
考虑可访问性语义,我会使用 UL 作为容器而不是 DIV,问题就来了。事实证明,只有 UL 上的第一个 anchor 链接会按预期关闭,而其他 anchor 链接则不会。我不明白。
HTML
<section class="menu">
<!-- close menu -->
<button class="menu__close">
<svg>...</svg>
</button>
<ul class="menu__content">
<li><a href="#seccion-inicio">Inicio</a></li>
<li><a href="#seccion-muestra">Muestras Web</a></li>
<li><a href="#seccion-servicio">Servicios Web</a></li>
<li><a href="#seccion-informacion">Información</a></li>
<li><a href="#seccion-contacto">Contacto</a></li>
</ul>
</section>
JS
document.querySelector(".menu__content a").onclick = function() {
document.querySelector(".menu").style.height = "0%";
}
最佳答案
你可以在这里看到
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
"The Document method querySelector() returns the first Element within the document that matches the specified selector"
您可以改为使用 querySelectorAll,然后迭代集合以附加您的点击处理程序,不需要 JQuery。
let myAList = document.querySelectorAll(".menu__content > li > a")
for (var i = 0; i < myAList.length; i++) {
myAList[i].onclick = function() {
console.log("Click");
document.querySelector(".menu").style.height = "0%";
}
}
关于javascript - 汉堡 : Full screen navigation menu with UL as anchor container,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61504057/