当前,以下脚本默认情况下显示内容。我该如何调整代码,使其默认处于隐藏状态,为了隐藏或显示它,必须单击按钮。
<script>
function myFunction_1() {
var x = document.getElementById("myDIV");
var y = document.getElementById("myDIV2");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function myFunction_2() {
var y = document.getElementById("myDIV2");
if (y.style.display === "none") {
y.style.display = "block";
} else {
y.style.display = "none";
}
}
<script>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction_1()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<br><br>
<button onclick="myFunction_2()">Try it 2</button>
<div id="myDIV2">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
答案 0 :(得分:3)
只需在每个元素上将display: none
设置为嵌入式样式即可。
<div id="myDIV" style="display: none;">
This is my DIV element.
</div>
<br><br>
<button onclick="myFunction_2()">Try it 2</button>
<div id="myDIV2" style="display: none;">
This is my DIV element.
</div>
实时示例:
function myFunction_1() {
var x = document.getElementById("myDIV");
var y = document.getElementById("myDIV2");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function myFunction_2() {
var y = document.getElementById("myDIV2");
if (y.style.display === "none") {
y.style.display = "block";
} else {
y.style.display = "none";
}
}
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction_1()">Try it</button>
<div id="myDIV" style="display: none;">
This is my DIV element.
</div>
<br><br>
<button onclick="myFunction_2()">Try it 2</button>
<div id="myDIV2" style="display: none;">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>