简体   繁体   中英

How to set initial state of div element to hide

我创建了一个简单的函数,它在单击按钮时显示或隐藏 div 标签,但如何将其设置为最初隐藏并在单击按钮后显示?

function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  };

 function toggle() { document.getElementById('test').style.display = 'block'; }
 .hide { display: none; }
 <div id="test" class="hide">Test</div> <button onclick="toggle()">Toggle</button>

 function btnClick(){ const divElement = document.getElementById('myDiv'); if (divElement.classList.contains("show")) { divElement.classList.remove("show") divElement.classList.add("hide") } else { divElement.classList.add("show") divElement.classList.remove("hide") } }
 .hide{ display: none } .show{ display: block }
 <div id="myDiv" class="hide"> Hello, I am Div HTML Content </div> <button onclick="btnClick()">Click Me!!</button>

Just set it's display style property to None .

 element = document.getElementById('toggle'); button = document.getElementById('toggle-button'); function hideAndShow(){ if(element.style.display == 'none'|| element.style.display == '') // checks if the display property is set to none or not { element.style.display = 'Block'; // if set to none then set the display property to block button.innerHTML = 'Hide'; // changes the button's text } else{ element.style.display = 'None'; // otherwise set it to none button.innerHTML = 'Show'; } }
 #toggle{ width: 100%; margin: auto; height: 50px; display: None; /*this set's the divison to a hidden state by default*/ background-color: rgba(248,25,34,0.8); } #toggle-button{ width: 100%; margin: 5px; height: 25px; padding: 5px; color: rgba(25,25,67,0.5); }
 <div id='toggle'></div> <button id='toggle-button' onclick='hideAndShow()'>Show</button>

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