我正在学习如何编程,我想使用 JavaScript 在隐藏和显示元素之间切换。该脚本如下所示。它有效,但我不想在程序运行后显示解决方案,而是希望将其隐藏,以便用户可以单击并查看解决方案。我想反过来。我尝试过使用“display:none”,但它停止工作。我知道这很容易,但我无法让它发挥作用。你能帮我吗?
function SolutionFunction() {
var x = document.getElementById("solution");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
#solution {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<button onclick=" SolutionFunction ()">Try it</button>
<div id=" solution ">
This is the solution.
</div>
最佳答案
默认情况下,当您使用 x.style.display 获取它时,display
参数为空,因为这仅查看元素属性,而不查看 CSS 样式。所以你可以检查它是否为空。
并且您需要删除 id
周围的空格才能使其正常工作。
function SolutionFunction() {
var x = document.getElementById("solution");
if (x.style.display === "") {
x.style.display = "block";
} else {
x.style.display = "";
}
}
#solution {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
display: none;
}
<button onclick=" SolutionFunction ()">Try it</button>
<div id="solution">
This is the solution.
</div>
或者您将 display: none
放入元素的 style
属性中,您的代码也将起作用:
function SolutionFunction() {
var x = document.getElementById("solution");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
#solution {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<button onclick=" SolutionFunction ()">Try it</button>
<div id="solution" style="display: none;">
This is the solution.
</div>
关于javascript - 在隐藏和显示元素之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51707790/