为什么我的显示隐藏按钮需要在第一次时双击 [英] Why my show hide button needs double-click on first time
问题描述
我的网站上有此显示/隐藏"按钮.它可以工作,但是第一次用户需要双击它,就好像开关被设置为"hide"但该元素已经被隐藏了.
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
我是javascript的新手,所以我不知道如何更改它.
I'm new to javascript, so I don't know how to change this.
谢谢
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>
推荐答案
要获得预期的结果,请使用以下检查显示内容的选项,如果不是内联的,则显示为空
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 === ""
请参阅此链接以获取更多详细信息-为什么在CSS中提供样式时element.style总是返回空?
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>
这篇关于为什么我的显示隐藏按钮需要在第一次时双击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!