首页 > 解决方案 > javascript计时器和html进度条替换html

问题描述

大家好,在 html 页面上有一个简单的 javascript 倒数计时器和一个 html 进度条。

只有在进度条完成后,我才弄清楚如何让脚本用不同的页面替换 html 页面。

它要么几乎立即替换页面,要么根本不替换页面,或者根据我尝试过的不同事情,进度不会移动有人可以帮助我......这是当前代码。

var timeleft = 10;

var downloadTimer = setInterval(function() {
  document.getElementById("progressBar").value = 10 - --timeleft;
  if (timeleft <= 0)
    clearInterval(downloadTimer);
}, 1000);

if (document.getElementById("progressBar").value > 10) {
  window.location.replace('download.html');
}
<center><progress value="0" max="10" id="progressBar" style="margin-top: -29px; height: 10px;"></progress></center>

标签: javascripthtml

解决方案


if(document.getElementById("progressBar").value > 10){...}不在你的区间内,这意味着它只运行一次,就在区间创建之后。

此外,document.getElementById("progressBar").value永远不会达到大于 的值10。它恰好到达10,但您的间隔已被告知停止。

考虑一下:

const progressEl = document.getElementById("progressBar");

let downloadTimer = setInterval(() => {
  progressEl.value++;

  if (progressEl.value >= progressEl.max) {
    clearInterval(downloadTimer);
    console.log("Would replace");
  }
}, 200);
<progress value="0" max="10" id="progressBar"></progress>


推荐阅读