JavaScript中“ display.style”的作用是什么?

问题描述 投票:-3回答:2

我正在练习拨动开关功能。...

完整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

javascript html css toggle
2个回答
0
投票


0
投票

[使用您的代码,每当您第一次单击时-myIDV.style.display返回一个空字符串"",为此它转到else块,将内联样式设置为block,但是它已经具有此样式。因此您不会得到任何样式可见的效果。第一次单击后,它会随心所欲。

© www.soinside.com 2019 - 2024. All rights reserved.