我想在按下按钮时显示一个元素。默认显示元素,如何让它默认显示 none?

I want to make an element display when a button is pressed. by default the element is shown, how do I make it display none by default?

按钮的所有内容似乎都是正确的,而且它的工作方式与我目前想要的相反。当我加载页面时 div: myDIV 在那里,按钮切换它消失和重新出现。如何使 myDIV 默认设置为 none,但仍具有按钮功能作为切换

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


<button onclick="myFunction()">test</button>

<div id="myDIV">
This is my DIV element.
</div>



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

我觉得重点就在这里style.display = '' actually do

使用style.display获取显示状态时,无法获取css

中定义的显示属性

您需要先获取 CSS 值才能使用 JS 中的按钮切换显示值。默认情况下,建议不要在 HTML 上提供内联样式。

function myFunction() {
 const cont = document.querySelector("#chartContainer");
 const styles = getComputedStyle(cont)
  const displayStyle = styles.display;
  if(displayStyle === "none"){
   cont.style.display = "block";
  }else {
   cont.style.display = "none";
  }
  
}

const BTN = document.querySelector("button");
BTN.addEventListener('click', myFunction);
.container {
  background-color: #FFF;
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  display: flex;
}

#chartContainer {
  background-color: blue;
  border-radius: 25px;
  height: 200px;
  width: 100%;
  float: below;
  display: none;
}

button {
  width: 50px;
  height: 50px;
}
<div class="container">
    <button>toggle</button>
    <div id="chartContainer">
    </div>
    <script src="https://canvasjs.com/assets/script/canvasjs.min.js"> </script>
</div>