javascript - 为什么div不会消失?

标签 javascript html

<分区>

为什么当我尝试隐藏一个 div 时 运行它不会消失吗?据我了解,您可以使用 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>

最佳答案

使用 setTimeout() 方法代替 someComplicatedFunction() 方法。

As JavaScript only has a single thread and method will execute asynchronously so webpage will be unresponsive while the script is running. This is the reason we can't see the data changes if use someComplicatedFunction() method as dom manipulation done within a ms and page become unresponsive while executing that method for 3 seconds.

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>

关于javascript - 为什么div不会消失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45221759/

相关文章:

javascript - 如何在 Vue 中动态标记或标记 DOM 元素

javascript - 显示问题 :none for some ajax content and a javascript toggle function

javascript - 如何使用文本输入更改 iframe 的 src?

javascript - 使用 AngularJS 指令更改 ng-repeat 元素的类

javascript eval() 方法在过滤时降低了性能

javascript - Node.js Promise 引用错误

javascript - 选择materializecssCSS

javascript - JavaScript 中的学生注册表验证

python - 如何使用 to_html 将 CSS 类(我的风格)应用到 Pandas DataFrame

html - rails : Converting a text field's linebreaks into <br/>