javascript - 为什么我的显示隐藏按钮第一次需要双击
问题描述
我的网站上有这个显示/隐藏按钮。它可以工作,但是用户第一次需要双击它,好像开关设置为“隐藏”但元素已经隐藏了......
我想编辑我的代码,以便按钮第一次单击即可显示元素
我是 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 === ""
请参阅此链接以获取更多详细信息 -为什么在 CSS 中提供样式时 element.style 总是返回空?
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>
推荐阅读
- c# - .NET Core 2.2 - 无法从 Azure AppConfig 获取应用配置
- django - Django 自定义用户模型创建 NOT NULL 约束失败错误
- c - 在 C 中多次使用 Ctrl+C
- python - 从 pdf 中删除打印机裁剪标记
- r - Create a new column based on conditional statement of another column R
- c - 代码只取输入值然后什么都没有发生
- assembly - 程序集使用调用 scanf 输入编号
- node.js - I encountered an error that could not find the npm and node on the server. /usr/bin/env: node: No such file or directory
- c++ - C ++和ncurses - 停止按键中断键保持
- python - 如何从加载的页面中选择所有推文?