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

被刻印的时光 ゝ 提交于 2021-02-08 10:58:52

问题


I have this show/hide button on my website. It works, but on the first time the user needs to double-click it as if the switch is set to "hide" but the element is already hidden...

I'd like to edit my code so the button shows the element with a single click on the first time

I'm new to javascript, so I don't know how to change this.

Thank you

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>

回答1:


To achieve expected result, use below option of checking display initially which will be empty if it is not inline

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

Please refer this link for more details - 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>



回答2:


Because initially x.style.display === "none" is false and it goes to else block.
You can use ternary operator for this purpose.

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>

The code works because '' is falsy value




回答3:


You need to check your "if/then" statement. You are checking the wrong order.

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>


来源:https://stackoverflow.com/questions/55071684/why-my-show-hide-button-needs-double-click-on-first-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!