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

标签 html css display

我正在尝试显示和隐藏 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>

关于HTML - 通过不显示隐藏和取消隐藏 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50158365/

相关文章:

javascript - 如何使用 innerHTML 更改文本不透明度?

javascript - 将图像和文本一起附加到javascript中的列表

python - 显示 json python discord bot

javascript - redux-状态发生变化但组件不显示重新渲染的 View

html - CSS 动画在 Chrome 中有效,但在 FireFox 中无效

javascript - HTML5 两个或多个导入

选择框内的 HTML <br/>

html - 通过 CSS 属性换行?

html - 如何在css中使图像全屏显示?

html - 如何对齐显示元素?