为什么我的显示隐藏按钮需要第一次双击

Why my show hide button needs double-click on first time

我的网站上有这个 show/hide 按钮。它有效,但第一次用户需要双击它,就好像开关设置为 "hide" 但元素已经隐藏...

我想编辑我的代码,以便按钮在第一次单击时显示元素

我是 javascript 的新手,所以我不知道如何更改它。

谢谢

function showhidemenu() {
  var x = document.getElementById("menu");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
#menu {
  background: rgba(0, 0, 0, 0);
  position: absolute;
  z-index: 1;
  top: 60px;
  right: 50px;
  width: 150px;
  font-family: 'Open Sans', sans-serif;
  display: none;
}
<div id="menu">This is a menu</div>
<button onclick="showhidemenu()">Show/hide</button>

您需要检查您的 "if/then" 声明。您检查的顺序有误。

function showhidemenu() {
  var x = document.getElementById("menu");
  if (x.style.display == "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}
#menu {
  background: rgba(0, 0, 0, 0);
  position: absolute;
  z-index: 1;
  top: 60px;
  right: 50px;
  width: 150px;
  font-family: 'Open Sans', sans-serif;
  display: none;
}
<div id="menu">This is a menu</div>
<button onclick="showhidemenu()">Show/hide</button>

因为最初 x.style.display === "none"false 并且它进入 else 块。
为此,您可以使用 三元运算符

function showhidemenu() {
  var x = document.getElementById("menu");
  x.style.display = !x.style.display ? 'block' : '';
}
#menu {
  background: rgba(0, 0, 0, 0);
  position: absolute;
  z-index: 1;
  top: 60px;
  right: 50px;
  width: 150px;
  font-family: 'Open Sans', sans-serif;
  display: none;
}
<div id="menu">This is a menu</div>
<button onclick="showhidemenu()">Show/hide</button>

代码有效,因为 '' 是虚假值

为了达到预期的结果,使用下面的选项来检查初始显示,如果它不是内联的,它将是空的

x.style.display === "none" || x.style.display === ""

请参阅此 link 了解更多详情 -

function showhidemenu() {
  var x = document.getElementById("menu");
  if (x.style.display === "none" || x.style.display === "") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
#menu {
  background: rgba(0, 0, 0, 0);
  position: absolute;
  z-index: 1;
  top: 60px;
  right: 50px;
  width: 150px;
  font-family: 'Open Sans', sans-serif;
  display: none;
}
<div id="menu">This is a menu</div>
<button onclick="showhidemenu()">Show/hide</button>