我正在尝试制作节目&隐藏div
。我使用了来自w3schools
(https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_toggle_hide_show)的教程,但是在这里已经显示了div,然后隐藏它,而我的隐藏然后显示。因此,在示例中,我只需将display: none;
添加到#myDIV
:
<!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;
display: none;
}
</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>
当我第一次点击Try it
按钮时,div
没有显示...为什么?从那时起,如果我重新点击它会显示并正常消失......我该如何解决这个问题? TY
答案 0 :(得分:2)
因为第一次没有定义x.style.display
!
将您的条件修改为if (x.style.display === "none" || !x.style.display)
<!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;
display: none;
}
</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>
&#13;
答案 1 :(得分:0)
在#myDIV下,您已设置display: none
删除该行,它会自动显示