我正在练习拨动开关功能。...
完整HTML代码
<!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="block"
}
</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() {
if (myDIV.style.display == "block") {
myDIV.style.display = "none";
} else {
myDIV.style.display = "block";
}
}
</script>
</body>
</html>
为了使div元素消失,我必须单击两次(仅在页面首次加载时)。我可以通过将CSS display设置为none;
而不是`block; *来修复它。是什么原因造成的?
此外,我已经意识到在myDIV.style.display
后加上===或==或=的符号会导致不同的结果。我想知道为什么会这样?
ps.s。我正在尝试的原始内容是:https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_toggle_hide_show
[使用您的代码,每当您第一次单击时-myIDV.style.display
返回一个空字符串""
,为此它转到else块,将内联样式设置为block,但是它已经具有此样式。因此您不会得到任何样式可见的效果。第一次单击后,它会随心所欲。