简体   繁体   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?

All the stuff for the button seems right and it works in reverse of what I want currently. 该按钮的所有内容似乎正确,并且与我当前想要的相反。 when I load the page the div: myDIV is there and the button toggles it disappearing and reappearing. 当我加载页面div时:myDIV在那并且按钮切换它消失并重新出现。 How do I make myDIV none by default but still have the button function as a toggle 如何默认使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>

I think the point is in here style.display = '' actually do 我认为关键是在这里style.display =''实际上

When you use style.display to get display status, it can not get display attribute defined in css 使用style.display获取显示状态时,无法获取CSS中定义的显示属性

You need to get CSS Value first to toggle the display value with a button in JS. 您需要先获取CSS值,才能使用JS中的按钮切换显示值。 By default, it is advised not to give inline style on HTML. 默认情况下,建议不要在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