我有一个网页,用户可以在其中从菜单中选择一些选项。每个选项都需要几秒钟的时间才能下载、处理和显示。所以这段时间我尝试展示一个 loader gif。但我遇到了一些奇怪的问题并且陷入了困境。
我创建了一个非常简单的jsfiddle ,删除除最小代码之外的所有内容以重现问题:
$('#ActnBtn').click(function() {
document.getElementById("loading").style.display = "block";
console.log("loader should be showed");
//Intensive code simulation, probably you should adjust the "times" value to the power of your device
var times = 5000000000;
for (let i = 0; i < times; i++) {
var j = (i ^ 2 + 1) / (i - 1) ^ 2;
}
console.log("finished")
setTimeout(function() {
document.getElementById("loading").style.display = "none";
}, 1000);
// 1sec timeout to be able to see the loader
// document.getElementById("loading").style.display = "none"
// Without timeout loader isn't showed because "show" and "hide" happens at the same time
});
#loading {
display: none;
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url(https://media.giphy.com/media/lrnlLO9o53qH44g7kC/giphy.gif) center no-repeat #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=loading></div>
<button id="ActnBtn" type="button">Do some intesive work</button>
历史悠久,加载程序显示在“密集代码”之后。对我来说这完全没有意义,我现在不知道如何继续。任何帮助表示赞赏。非常感谢。
问候,
赫克托
PD:控制台显示如下消息:[违规]“点击”处理程序花费了 4370 毫秒
最佳答案
这部分 JavaScript 是同步运行的。
您还需要将密集型代码放入 setTimeout 中。
这是因为 DOM 的更改将在 javascript 返回并完成后发生。
请在这里找到正确的示例(使用忍者,因为我没有运行你的 gif),我将你的迭代放入计时器等函数中。
$('#ActnBtn').click(function() {
document.getElementById("loading").style.display = "block";
console.log("loader should be showed");
setTimeout(function(){
//Intensive code simulation, probably you should adjust the "times" value to the power of your device
var times = 5000000000;
for(let i=0; i<times; i++){
var j = (i^2+1)/(i-1)^2;
}
console.log("finished")
setTimeout(function(){document.getElementById("loading").style.display = "none";},1000); //1sec
},0);
});
#loading {
display: none;
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('https://loading.io//assets/img/pricing/ninja.gif') center no-repeat #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=loading></div>
<button id="ActnBtn" type="button">Do some intesive work</button>
我希望这对您有所帮助并给出足够的解释。
关于javascript - 在密集代码片段之前使用加载器进行 style.display 的 JS 奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58084047/