【问题标题】:Why my show hide button needs double-click on first time为什么我的显示隐藏按钮第一次需要双击
【发布时间】:2019-07-30 23:39: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>
【问题讨论】:
标签:
javascript
html
css
button
show-hide
【解决方案1】:
为了达到预期的效果,请使用下面的选项检查初始显示,如果不是内联则为空
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>
【解决方案2】:
因为最初 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>
代码有效,因为'' 是假值
【解决方案3】:
您需要检查您的“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>