javascript - 在隐藏和显示元素之间切换

标签 javascript html

我正在学习如何编程,我想使用 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/

相关文章:

javascript - 在 PhoneGap Build 应用程序中使用正确的库和 scandit

javascript - 为什么我在 php 中看到 html 标签使用tinymce textarea 作为输入?

javascript - 为图片生成框架

javascript - 如何清除第一次关注的输入?

html - 使网站动态化,以便跨屏幕工作

javascript - 三.js:如何将相同大小的对象放在屏幕顶部

javascript - 无法删除 [object Array] 的属性 '1'

asp.net - <img src =""> 会影响性能吗?

ASP.NET 服务器端显示 JS 警报框,使用部分回发时不起作用

html - 高度 : 100% or min-height: 100% for html and body elements?