繁体   English   中英

我想在按下按钮时显示元素。 默认情况下显示该元素,如何使其默认不显示?

[英]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不设置,但仍具有按钮功能作为切换

<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 =''实际上

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM