我正在尝试创建一个按钮来显示或隐藏我的 div 元素,以便使用同一按钮打开和关闭它。我不明白为什么它不起作用,当我单击按钮时没有任何反应,有人可以帮助我吗?
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
width: 500px;
height: 500px;
background-color: lightblue;
display: none;
}
</style>
</head>
<body>
<p>Click the "Try it" button to set the display property of 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>
var div_aperto = false;
function myFunction(div_aperto)
if (div_aperto) {
div_aperto = false;
document.getElementById("myDIV").style.display = "none"; }
else { div_aperto = true;
document.getElementById("myDIV").style.display = "block"; }
</script>
</body>
</html>
最佳答案
函数语句没有括号,也不需要参数
function myFunction() {
if (div_aperto) {
div_aperto = false;
document.getElementById("myDIV").style.display = "none"; }
else { div_aperto = true;
document.getElementById("myDIV").style.display = "block"; }
}
关于带有 boolean 值的 JavaScript if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48624029/