简体   繁体   中英

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. How do I make myDIV none by default but still have the button function as a toggle

<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

When you use style.display to get display status, it can not get display attribute defined in css

You need to get CSS Value first to toggle the display value with a button in JS. By default, it is advised not to give inline style on 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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