我在 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>
但它是捉迷藏。我应该如何修改它以便我可以做相反的事情?先显示然后隐藏切换?
答案 0 :(得分: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>
答案 1 :(得分:0)
我建议在你的 css 中添加另一个类
.is-hidden
{
display:none;
}
然后简单地在 is-hidden 和 nothing 之间切换
document.getElementById("#myDIV").classList.toggle("is-hidden");
如果你想从一个隐藏的 div 开始,只需在定义中添加 is-hidden 类
<div id="myDIV" class="is-hidden">
This is my DIV element.
</div>