我正在创建一个第一次的网站,希望有一个0-100%的进度条,它在开始时有几秒钟的延迟可先淡入(我可以在CSS中这样做),但是进度条脚本在我放置以下内容时似乎不会延迟:
HTML:
<div class="loading">
<div class="percent">100%</div>
<div class="progress-bar">
<div class="progress"></div>
</div>
</div>Javascript:
var percent = document.querySelector(".percent");
var progress = document.querySelector(".progress");
var count = 1;
var per = 1;
var loading = setInterval(animate, 25);
setTimeout(animate, 2000);
function animate() {
if (count == 100 && per == 100) {
clearInterval(loading);
} else {
per = per + 1;
count = count + 1;
progress.style.width = per + "px";
percent.textContent = count + "%";
}
} 我试过这一点,但这甚至没有动画的进展栏:
setTimeout(function animate() {
if (count == 100 && per == 100) {
clearInterval(loading);
} else {
per = per + 1;
count = count + 1;
progress.style.width = per + "px";
percent.textContent = count + "%";
}
}, 2000);我还尝试过将setTimeout放入名为timeInMilliseconds设置为2000的变量中,并将其替换为时间,但这是行不通的。
很抱歉,如果答案真的很明显的话,这都是新的,我已经从教程中学到了尽可能多的东西。提前谢谢。
发布于 2020-09-25 20:55:25
你离我这么近!
所有相关行动都发生在这里:
var loading = setInterval(animate, 25);
setTimeout(animate, 2000);正在发生的事情是:一旦对var loading = setInterval(animate, 24);进行了评估,浏览器就开始每24 is调用一次animate函数。然后,2秒后,它再次调用animate (然而,这一次它没有做任何新的事情,因为count和per仍然等于100)。
下面是一个解决方案,一步一步地解决:
,
setTimeout(() => {
// we want to start our animation loop here
}, 2000);,
setTimeout的函数的主体是什么?这是您前面已经写过的循环逻辑:setTimeout(() => {
loading = setInterval(animate, 25);
}, 2000);总之,这个片段现在等待2秒,然后开始循环您的animate函数。
最后一件事!即使在超时期间才分配loading,我们仍然需要在全局范围内声明它(这样animate就可以访问它)。所以我们的修订如下:
var percent = document.querySelector(".percent");
var progress = document.querySelector(".progress");
var count = 1;
var per = 1;
var loading; // <- Still declared in the global scope
setTimeout(() => {
loading = setInterval(animate, 25);
}, 2000);
function animate() {
if (count == 100 && per == 100) {
clearInterval(loading);
} else {
per = per + 1;
count = count + 1;
progress.style.width = per + "px";
percent.textContent = count + "%";
}
} 发布于 2020-09-25 20:43:17
您需要一个在2秒后调用setInterval的函数。从那里调用setInterval,并将loading分配给间隔。loading变量是全局的,所以animate也可以访问它。
然后使用setTimeout函数调用启动动画的函数来设置延迟。
var percent = document.querySelector(".percent");
var progress = document.querySelector(".progress");
var count = 1;
var per = 1;
var loading;
setTimeout(startAnimation, 2000);
function startAnimation() {
loading = setInterval(animate, 25);
}
function animate() {
if (count == 100 && per == 100) {
clearInterval(loading);
} else {
per = per + 1;
count = count + 1;
progress.style.width = per + "px";
percent.textContent = count + "%";
}
}.progress {
height: 10px;
width: 0px;
background-color: green;
}
.progress-bar {
width: 100px;
background-color: grey;
}<div class="loading">
<div class="percent">0%</div>
<div class="progress-bar">
<div class="progress"></div>
</div>
</div>
https://stackoverflow.com/questions/64071008
复制相似问题