HTML - 通过显示 none 隐藏和取消隐藏 div

HTML - Hide and unhide div by display none

我正在尝试表演和隐藏 div。我使用 w3schools (https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_toggle_hide_show) 中的教程,但在此 div 已经显示,然后您将其隐藏,而我的是隐藏然后显示。所以在这个例子中,我只是将 display: none; 添加到 #myDIV:

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    #myDIV {
      width: 100%;
      padding: 50px 0;
      text-align: center;
      background-color: lightblue;
      margin-top: 20px;
      display: none;
    }
  </style>
</head>

<body>

  <p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>

  <button onclick="myFunction()">Try it</button>

  <div id="myDIV">
    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>

  <script>
    function myFunction() {
      var x = document.getElementById("myDIV");
      if (x.style.display === "none") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }
  </script>

</body>

</html>

当我第一次点击 Try it 按钮时 div 没有显示...为什么?从那时起,如果我重新单击它,它会正常显示和消失......我该如何解决这个问题?泰

因为第一次,x.style.display没有定义!

将您的条件修改为if (x.style.display === "none" || !x.style.display)

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    #myDIV {
      width: 100%;
      padding: 50px 0;
      text-align: center;
      background-color: lightblue;
      margin-top: 20px;
      display: none;
    }
  </style>
</head>

<body>

  <p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>

  <button onclick="myFunction()">Try it</button>

  <div id="myDIV">
    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>

  <script>
    function myFunction() {
      var x = document.getElementById("myDIV");
      if (x.style.display === "none" || !x.style.display) {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }
  </script>

</body>

</html>

在 #myDIV 下你设置了 display: none 删除该行,它将自动显示