在 HTML 中隐藏和显示 Div 标签

Par*_*ode 6 html javascript css

在这里,我试图隐藏该块,但第一次我需要在每次刷新页面时双击该按钮。我在下面附上了我的代码以供参考。

<!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>
Run Code Online (Sandbox Code Playgroud)

为什么会这样?有人可以让我知道我在哪里犯了错误吗?

ars*_*sho 1

第一次单击时,由于 CSS 的原因,页面上找不到 div 元素display: none。所以第一个 if 块没有被执行。它将元素设置displaynone第一次单击,第二次单击时将值更改为block

因此,我们需要在第一次点击时检查display属性值是否为none""

<!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>
Run Code Online (Sandbox Code Playgroud)