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

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

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

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

我是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>
javascript html css button show-hide
3个回答
2
投票

要获得预期的结果,请使用以下选项初始检查显示,如果它不是内联的,则为空

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

请参阅此链接了解更多详情 - Why element.style always return empty while providing styles in CSS?

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>

0
投票

您需要检查“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>

0
投票

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

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

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