我必须单击我的汉堡栏导航两次才能触发事件监听器

时间:2019-02-25 00:39:00

标签: javascript html

很抱歉这个基本问题,但是我是JS新手。我正在尝试创建一个汉堡栏导航菜单。它可以工作,但是...在页面加载时,我必须先两次单击导航按钮,然后才能触发它。我无法解决如何停止这种行为。

谢谢。

const burgerBarButton = document.getElementById("burgerNavigationButton");
console.log(burgerBarButton + "initilised");
const navigationMenu = document.getElementById("mainNavID");
console.log(navigationMenu + "initilised");

burgerBarButton.addEventListener('click', () => {
"use strict";
console.log('click outside of IF');
if(navigationMenu.style.display === "none"){
    navigationMenu.style.display = "block";
    console.log('click inside of IF');
}else{
    navigationMenu.style.display = "none";
}
});
<img class="" id="burgerNavigationButton" src="Images/burgerMenu/BurgerMenu---25x25.png" alt="Navigation Button"/>

<nav id="mainNavID" class="mainNav">
    <ul>
        <li id="homeNavigationLink"><div class="liDiv">Home</div></li>
        <li id="newsNavigationLink"><div class="liDiv">News</div></li>
        <li id="reviewsNavigationLink"><div class="liDiv">Reviews</div></li>
        <li id="techbyteNavigationLink"><div class="liDiv">TechByte</div></li>
    </ul>
</nav>

1 个答案:

答案 0 :(得分:0)

我将分配一个类,而不是比较display属性。如果您使用display属性,如果有人决定将您的导航样式设置为例如,可能会遇到麻烦。 display: flex。因此,请尽量避免在JS和CSS中使用样式。

您可以执行以下操作:

const burgerBarButton = document.getElementById("burgerNavigationButton");

burgerBarButton.addEventListener('click', () => {
  let mainMenu = document.getElementById("mainNavID");
  mainMenu.classList.toggle('closed');
});
#mainNavID.closed{
  display: none;
}
<img class="" id="burgerNavigationButton" src="Images/burgerMenu/BurgerMenu---25x25.png" alt="Navigation Button"/>

<nav id="mainNavID" class="mainNav">
    <ul>
        <li id="homeNavigationLink"><div class="liDiv">Home</div></li>
        <li id="newsNavigationLink"><div class="liDiv">News</div></li>
        <li id="reviewsNavigationLink"><div class="liDiv">Reviews</div></li>
        <li id="techbyteNavigationLink"><div class="liDiv">TechByte</div></li>
    </ul>
</nav>