问题
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