显示样式不会改变

问题描述 投票:0回答:2

const hamburgerMenuBtn = document.getElementById("hamburger-menu-button");

hamburgerMenuBtn.addEventListener("click", function() {
  hamburgerPopupToggle()
});

function hamburgerPopupToggle() {
  console.log("Button pressed");
  const hamburgerMenuPopup = document.getElementById("hamburger-menu-popup");
  if (hamburgerMenuPopup.style.display === "block") {
    hamburgerMenuPopup.style.display = "none";
    console.log(hamburgerMenuPopup.style.display);
  } else {
    hamburgerMenuPopup.style.display = "block";
    console.log(hamburgerMenuPopup.style.display);
  }
}
#hamburger-menu-popup { display: none; }
<div class="hamburger-menu">
  <span id="hamburger-menu-button">menu</span>
  <div id="hamburger-menu-popup">
    <div id="home-button">Home</div>
    <div id="create-post">Create a Post</div>
  </div>
</div>

弹出窗口打开 (https://i.sstatic.net/4hlVl4VL.png) 但是,它不是将显示样式设置回“无”,而是将其设置为“取消设置!重要”,但它记录它是“无”(https://i.sstatic.net/DadeuwQ4.png)( https://i.sstatic.net/bmL9RzHU.png

因此,由于某种原因它记录了应该发生的事情,但 CSS 没有任何改变。 (有变化,但没有想象中的那么好)

javascript css button display styling
2个回答
1
投票

您的代码对我来说工作正常,因此可能还有其他原因导致您出现问题(可能是某些插件?)。

我建议只在菜单元素上切换一个类。这有两个优点:

  1. 你的 JS 代码中不需要 if
  2. 您可以在 CSS 中完成所有样式

JS:

let hamburgerMenuPopup = document.getElementById("hamburger-menu-popup");
hamburgerMenuPopup.classList.toggle("show");

CSS:

#hamburger-menu-popup{
display:none;
}

#hamburger-menu-popup.show{
display:block;
}

-2
投票

请尝试这样:

const hamburgerMenuBtn = document.getElementById("hamburger-menu-button");

hamburgerMenuBtn.addEventListener('click', event => {
   let hamburgerMenuPopup = document.getElementById("hamburger-menu-popup");
    if (hamburgerMenuPopup.style.display === "none") {
        document.getElementById("hamburgerMenuPopup").style.display = "block";
    } else {
        document.getElementById("hamburgerMenuPopup").style.display = "none";
    }
});

const hamburgerMenuBtn = document.getElementById("hamburger-menu-button");

hamburgerMenuBtn.addEventListener('click', event => {
   let hamburgerMenuPopup = document.getElementById("hamburger-menu-popup");
    if (hamburgerMenuPopup.style.display === "none") {
        document.getElementById("hamburgerMenuPopup").style.display = "block";
    } else {
        document.getElementById("hamburgerMenuPopup").style.display = "none";
    }
});
<div class="hamburger-menu">
  <span id="hamburger-menu-button">menu</span>
  <div id="hamburger-menu-popup">
    <div id="home-button">Home</div>
    <div id="create-post">Create a Post</div>
  </div>
</div>

#hamburger-menu-popup { display: none; }

© www.soinside.com 2019 - 2024. All rights reserved.