简体   繁体   English

如何将按钮更改为而不是将div从可见更改为不可见,以做相反的事情?

[英]How can I change my button to instead of changing a div from visible to not visible, to do the opposite?

I have a button that changes the visibility of a div. 我有一个按钮,可更改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. 如何使div保持隐藏状态并在按下按钮时使其显示。

 <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: 您还可以通过调用Hide()函数在HTML代码的末尾添加<script>标记,如下所示:

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

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

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