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

IT技术 javascript html css button show-hide
2021-01-23 13:04:56

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

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

我是 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>

3个回答

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

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

请参阅此链接以获取更多详细信息 -为什么在 CSS 中提供样式时 element.style 总是返回空值?

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>

因为最初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>

该代码有效,因为它''是假值

您需要检查您的“如果/那么”语句。您正在检查错误的顺序。

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>