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

为什么div没有消失?[副本]

  •  1
  • user1762507  · 技术社区  · 7 年前

    它不会消失吗?我的理解是,你可以使用 document.getElementById('something').style.display = "none";

    	function someComplicatedFunction(ms) {
            // This isn't the exact function I am using, 
            // but it has a similar form and the same problem
            let start = new Date().getTime();
            let end = start;
            while (end < start + ms) {
                end = new Date().getTime();
            }
        }
        
        function hideTheOtherDiv() {
        	document.getElementById('div1').style.display = "none";
            document.getElementById('div2').style.display = "initial";
            console.log("Start");
    
            someComplicatedFunction(3000);
            
            console.log("end");
            document.getElementById('div1').style.display = "initial";
            document.getElementById('div2').style.display = "none";
        }
        
        document.getElementById('div2').style.display = "none";
    <!DOCTYPE html>
    <html>
    <body>
    
    <div id="div1">One</div>
    <div id="div2">Two</div>
    <button onclick="hideTheOtherDiv()">Switch</button>
    
    </body>
    
    <script type="text/javascript">
    
    
    </script>
    
    </html>
    2 回复  |  直到 7 年前
        1
  •  1
  •   Pawan Kumar    7 年前

    使用 setTimeout() 方法而不是 someComplicatedFunction()

    JavaScript只有一个线程,方法将执行 这就是为什么如果使用,我们看不到数据变化的原因 一些复杂的函数() ms 当执行该方法时,页面变得没有响应

    function hideTheOtherDiv() {
    
      document.getElementById('div1').style.display = "none";
      document.getElementById('div2').style.display = "initial";
      console.log("Start");
    
      setTimeout(function() {
        console.log("end");
        document.getElementById('div1').style.display = "initial";
        document.getElementById('div2').style.display = "none";
      }, 3000);
    }
    
    document.getElementById('div2').style.display = "none";
    <!DOCTYPE html>
    <html>
    
    <body>
    
      <div id="div1">One</div>
      <div id="div2">Two</div>
      <button onclick="hideTheOtherDiv()">Switch</button>
    
    </body>
    
    <script type="text/javascript">
    </script>
    
    </html>
        2
  •  0
  •   Jarek Kulikowski    7 年前
    function hideTheOtherDiv() {
        document.getElementById('div1').style.display = "none";
        document.getElementById('div2').style.display = "initial";
    
        setTimeout( function() {
            document.getElementById('div1').style.display = "initial";  
            document.getElementById('div2').style.display = "none";
        }, 3000);
    }