javascript - 汉堡 : Full screen navigation menu with UL as anchor container

标签 javascript html css html-lists

很长一段时间以来,我一直在我的网站上使用汉堡菜单,这是一个具有绝对定位的全屏导航覆盖层,其中导航打开是(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/

相关文章:

php - 具有鼠标悬停和移出功能的按钮

javascript - 如何 a.x = a = {n : b} work in JavaScript?

javascript - 在 JavaScript 中读取数组

javascript - 通过Xpath在另一个元素中查找一个元素

Javascript:鼠标悬停功能不适用于 div

ruby-on-rails - Rails 移动应用程序 : Inline styles better?

jquery - 如果将鼠标悬停在 <a> 上,如何在 div 中显示图像?

javascript - 使用 Angular 4 Form Group 编辑和添加新数据

javascript - 如何修复不需要的侧滚动条?

javascript - 有没有办法可以在链接标记中链接到本地​​常量文件