【问题标题】:How to Show and Hide? [duplicate]如何显示和隐藏? [复制]
【发布时间】:2021-05-27 13:55:50
【问题描述】:
我在https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_toggle_hide_show找到了一个例子
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
</style>
</head>
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
</body>
</html>
但它是隐藏和显示。我应该如何修改它以便我可以做相反的事情?先显示然后隐藏切换?
【问题讨论】:
标签:
javascript
html
show-hide
【解决方案1】:
首先,初始设置displa:none;,所以默认是隐藏的。
其次,在 if 语句 x.style.display === "" 中添加新规则,因为在第一次点击时是真的。
完整(工作)代码:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
display: none;
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
</style>
</head>
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none" || x.style.display === "") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
</body>
</html>
编辑:更好的解决方案
使用getComputedStyle(x).display代替x.style.display,所以不需要和空字符串比较。
更新代码:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
display: none;
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
</style>
</head>
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (getComputedStyle(x).display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
</body>
</html>
【解决方案2】:
我建议在你的 css 中添加另一个类
.is-hidden
{
display:none;
}
然后简单地在 is-hidden 和 nothing with 之间切换
document.getElementById("#myDIV").classList.toggle("is-hidden");
如果要从隐藏的 div 开始,只需在定义处添加 is-hidden 类
<div id="myDIV" class="is-hidden">
This is my DIV element.
</div>