首页 > 解决方案 > 为什么我的显示隐藏按钮第一次需要双击

问题描述

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

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

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

标签: javascripthtmlcssbuttonshow-hide

解决方案


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

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>


推荐阅读