我正在使用动画汉堡菜单(https://jonsuh.com/hamburgers/)打开全屏菜单。一切都按预期工作,但我无法弄清楚如何在单击时关闭菜单(当然也要反转动画)。
我能够使用JS添加类“ is-active”,并添加“ onclick =“ openNav()”效果很好,但似乎创建onclick =“ toggleNav()”可能更合适,我只是似乎无法弄清楚如何用JS编写代码。
function openNav() {
document.getElementById("popUpNav").style.height = "100%";
}
function closeNav() {
document.getElementById("popUpNav").style.height = "0%";
}
// Hamburger Menu Spin
var hamburger = document.querySelector(".hamburger");
hamburger.addEventListener("click", function() {
hamburger.classList.toggle("is-active");
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/hamburgers/0.9.3/hamburgers.css" rel="stylesheet"/>
<!-- Full Screen Navigation -->
<div id="primaryNav">
<nav>
<!-- Spinning Hamburger Button -->
<button class="hamburger hamburger--spin" type="button" aria-label="Menu" aria-controls="navigation" aria-expanded="false" onclick="openNav()">
<span class="hamburger-box">
<span class="hamburger-inner"></span>
</span>
</button>
<div id="popUpNav" class="overlay" onclick="closeNav()">
<div class="overlay-content">
<a href="#problemSolution" data-scroll onclick="closeNav()">Link 1</a>
<a href="#" data-scroll onclick="closeNav()">Link 2</a>
<a href="#" data-scroll onclick="closeNav()">Link 3</a>
<a href="#" data-scroll onclick="closeNav()">Link 4</a>
</div>
</div>
</nav>
</div><!-- End Primary Nav -->
答案 0 :(得分:0)
我做了什么:
无论何时单击汉堡包,我们都将检查它是否已经具有is-active
类。如果是这样,则表示菜单当前处于活动状态,在这种情况下,我们应该调用closeNav
。如果它没有is-active
类,则意味着我们应该调用openNav
。
closeNav
和openNav
将:
is-active
。PS:
0% height
还是100% height
。因此我将其更改为display block/none
只是为了向您展示它的工作原理。onclick
中删除了menu
属性,因为您已经有一个EventListener了。link
。
function openNav() {
hamburger.classList.add("is-active");
document.getElementById("popUpNav").style.display = "block";
}
function closeNav() {
hamburger.classList.remove("is-active");
document.getElementById("popUpNav").style.display = "none";
}
// Hamburger Menu Spin
var hamburger = document.querySelector(".hamburger");
hamburger.addEventListener('click', () => hamburger.classList.contains('is-active') ? closeNav() : openNav());
closeNav();
<link href="https://cdnjs.cloudflare.com/ajax/libs/hamburgers/0.9.3/hamburgers.css" rel="stylesheet"/>
<!-- Full Screen Navigation -->
<div id="primaryNav">
<nav>
<!-- Spinning Hamburger Button -->
<button class="hamburger hamburger--spin" type="button" aria-label="Menu" aria-controls="navigation"
aria-expanded="false">
<span class="hamburger-box">
<span class="hamburger-inner"></span>
</span>
</button>
<div id="popUpNav" class="overlay" onclick="closeNav()">
<div class="overlay-content">
<a href="#problemSolution" data-scroll onclick="closeNav()">Link 1</a>
<a href="#" data-scroll onclick="closeNav()">Link 2</a>
<a href="#" data-scroll onclick="closeNav()">Link 3</a>
<a href="#" data-scroll onclick="closeNav()">Link 4</a>
</div>
</div>
</nav>
</div><!-- End Primary Nav -->