请原谅我的糟糕标题,但现在,我什至不知道我不知道什么。
如果我有一个看起来像这样的 HTML 页面:
<html>
<head>
<script>
jQuery(document).ready(function(){
jQuery("#modalDiv").show();
//This part takes up to a few seconds to execute and blocks the browser
for(var i = 0; i < 10000; i++){
console.log("doing something");
}
jQuery("#modalDiv").hide();
});
</script>
<style>
#modalDiv{
background-color:red;
height:100px;
width:100px;
}
</style>
</head>
<body>
<div id="modalDiv"></div>
</body>
</html>
ID 为“modalDiv”的元素永远不会显示在页面上。我不是要解决这个“问题”,我只是想了解幕后发生的事情,导致我的脚本按原样运行。
最佳答案
在所有同步操作完成并且您的代码将控制权返回到主事件循环之前,浏览器不会呈现对 DOM 的更改。这使您可以在用户不看到所有中间表单的情况下对页面进行大量更改——它会等到您完成并显示最终结果。
强制立即更新的一种方法是使用动画。
$(function () {
jQuery("#modalDiv").show(5000);
//This part takes up to a few seconds to execute and blocks the browser
for (var i = 0; i < 10000; i++) {
console.log("doing something");
}
jQuery("#modalDiv").hide(5000);
});
关于javascript - 在阻塞代码之前和之后做一些事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17576513/