代码之家  ›  专栏  ›  技术社区  ›  darkchampionz

HTML-按显示隐藏和取消隐藏div无

  •  0
  • darkchampionz  · 技术社区  · 8 年前

    我想做一场秀&隐藏 div .我使用的教程来自 w3schools ( https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_toggle_hide_show )但在这里,div已经显示出来了,然后你把它隐藏起来,而我的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 按钮,然后 部门 不显示。。。为什么?从那时起,如果我重新单击它,它会正常显示和消失。。。我怎样才能解决这个问题?泰

    2 回复  |  直到 8 年前
        1
  •  2
  •   Saeed    8 年前

    因为第一次, 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>
        2
  •  0
  •   Dino the Dinosaur    8 年前

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

    推荐文章