javascript - 如何将 DIV 默认设置为 style.display = "none"?
问题描述
我正在尝试制作一个按钮,当它被点击时会显示其他文本,但是,我只能制作它
- a) 默认显示文本或
- b)默认隐藏文本,但按钮不起作用。
这是按钮的JS代码:
function showInfo() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div id="myDIV">
Hello World
</div>
<button type="button" class="btn btn-primary" click="showInfo()">
Show Info
</button>
有没有办法可以将默认 style.display 设置为 none?
解决方案
你的处理程序是click
. 它需要是onclick
。另外,我建议您添加一个带有的类display:none
,div
或者简单地内联它,如下所示:
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div id="myDIV" style="display: none">
Hello World
</div>
<button onclick="showInfo()">
Show Info
</button>
然后你的 JS 可以如下所示:
function showInfo() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
return x.style.display = "block";
}
return x.style.display = "none";
}
演示
function showInfo() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
return x.style.display = "block";
}
return x.style.display = "none";
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div id="myDIV" style="display: none">
Hello World
</div>
<button onclick="showInfo()">
Show Info
</button>
推荐阅读
- ios - 在 iOS 模拟器上部署 Delphi 应用程序时无法执行 /usr/bin/xcrun simctl install...
- shell - 使用 awk 拆分后删除特定列中的字符
- swift - 无法在捆绑包中加载 NIB - 捆绑包尚未加载
- bash - 读取文本文件以填充 bash 中的数组
- c++ - 如何将 QQuickItem 扩展作为子级添加到另一个 QQuickItem 扩展?
- c# - 从子表单调用父表单的点击事件,而无需更改父表单代码winform中的任何代码
- docker - Docker 环境变量
- java - 从远程服务器上的 Java SSH 运行 Oracle Exp 命令
- powershell - Powershell 参数集 - 两个带有强制/可选参数的可选集
- php - 在 3 个单词后裁剪字符串