我有一个按钮可以改变div的可见性。它会将它从可见变为隐藏,然后在每次按下时返回。如何使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>
发布于 2018-07-29 21:44:02
将样式添加到div - <div id="box" style ="display: none;">...</div>
发布于 2018-07-29 22:32:34
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>发布于 2018-07-29 21:50:37
您还可以像这样调用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>
https://stackoverflow.com/questions/51580905
复制相似问题