我的网站上有这个显示/隐藏按钮。它可以工作,但是第一次用户需要双击它,好像开关设置为“隐藏”但元素已经隐藏了......
我想编辑我的代码,以便按钮在第一次单击时显示该元素
我是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>
要获得预期的结果,请使用以下选项初始检查显示,如果它不是内联的,则为空
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>
您需要检查“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>
因为最初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>
该代码有效,因为''
是虚假价值