I have a button that changes the visibility of a div. It turns it from being visible to hidden and then back every time it's pressed. How can I make the div stay hidden and make the button show it when it's pressed.
<script> function Hide() { var x = document.getElementById("box"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } </script> <button id="Hidden" onclick="Hide()">Click me</button> <div id="box"> Sample text. </div>
将样式添加到div- <div id="box" style ="display: none;">...</div>
CSS - #box{display: none} //this will keep the element hidden on page load
function toggle() {
var state = document.getElementById("box").style.display;
if (state === "none") {
state = "block";
} else {
state = "none";
}
}
<button id="Hidden" onclick="toggle()">Click me</button>
<div id="box">
Sample text.
</div>
You can also add <script>
tag at the end of the HTML code with calling the Hide()
func Like this:
<script> function Hide() { var x = document.getElementById("box"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } </script> <button id="Hidden" onclick="Hide()">Click me</button> <div id="box"> Sample text. </div> <script>Hide();</script>
you can also add the inline display none as below
<script> function Hide() { var x = document.getElementById("box"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } </script> <button id="Hidden" onclick="Hide()">Click me</button> <div id="box" style="display:none"> Sample text. </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.