gpt4 book ai didi

HTML - 通过不显示隐藏和取消隐藏 div

转载 作者:太空宇宙 更新时间:2023-11-04 01:15:58 25 4
gpt4 key购买 nike

我正在尝试显示和隐藏 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 没有显示...为什么?从那时起,如果我重新单击它,它会正常显示和消失......我该如何解决这个问题?泰

最佳答案

因为第一次没有定义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>

关于HTML - 通过不显示隐藏和取消隐藏 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50158365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com