使用JavaScript反向隐藏/显示div

时间:2018-08-17 23:31:42

标签: javascript html

我需要制作一个hint按钮来隐藏然后显示的帮助。到目前为止,这是我的代码,但先显示然后隐藏。我不知道如何隐藏然后显示

<!DOCTYPE html>
<body>
<button onclick="myFunction()">HINT</button>
<div id="Hint">
<p>The hint</p>
</div>
<script>
function myFunction() {
var x = document.getElementById("Hint");
if (x.style.display === "none") {
    x.style.display = "block";
} else {
    x.style.display = "none";
}
}
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:5)

只需先隐藏div :)即可。

<div id="Hint" style="display: none;">
<p>The hint</p>
</div>

答案 1 :(得分:0)

<!DOCTYPE html>
<html lang="en">
<body>
  <button onclick="myFunction()">HINT</button>
  <div id="Hint" style="display: none;">
    <p>The hint</p>
  </div>
  <script>
    function myFunction() {
      var x = document.getElementById("Hint");
      if (x.style.display === "none") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }
  </script>
</body>
</html>