我的网站上有这个显示/隐藏按钮。它可以工作,但是第一次用户需要双击它,就好像开关设置为“隐藏”但元素已经隐藏......
我想编辑我的代码,以便按钮在第一次单击时显示该元素
我是 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 === ""
请参阅此链接了解更多详细信息 -为什么 element.style 在 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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句