选项卡不在焦点时进度条停止

Progress Bar stopping when tab is not in focus

我将以下代码用于进度条:

<div class="slide-progress-bar">
  <div class="progress-bar" id="progress-bar"></div>
  <!--progress-bar-->
</div>
<script>
var elem = document.getElementById("progress-bar");
var width = 1;

function progressBar() {
  resetProgressBar();

  id = setInterval(frame, 300);

  function frame() {
    if (width >= 100) {
      clearInterval(id);
    } else {
      width++;
      elem.style.width = width +"%";
    }
  }
}
function resetProgressBar() {
  width = 1;
  elem.style.width = width;
}
progressBar()
</script>
<style>
.slide-progress-bar {
  width: 150px;
  background-color:rgba(155, 155, 155, 0.36);
  transition: width 10s linear;
  display: inline-block;
  vertical-align: middle;
  margin: auto;
  width: 100%;
}

.progress-bar {
  height: 5px;
  background-color: #ff4546;
  position: relative;
  transition: linear;
}
</style>

它工作正常(当页面加载时,进度条开始并完成 300 帧)但是当我切换选项卡或最小化 window 它停止并且当我重新打开选项卡时,它恢复。我不希望这种情况发生。我希望进度条即使在未聚焦时也能继续加载。有办法吗?,因为我在许多其他网站上看到了这样的进度条。

您可以使用css3 transitions代替js动画来解决您面临的问题。 您可以阅读更多相关信息 here 添加示例供您参考。

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
 .slide-progress-bar {
  width: 150px;
  background-color:rgba(155, 155, 155, 0.36);
  transition: width 10s linear;
  display: inline-block;
  vertical-align: middle;
  margin: auto;
  width: 100%;
}

.slide-progress-bar .progress-bar {
  height: 5px;
  background-color: #ff4546;
  position: relative;
  transition: linear;
  animation: progres 4s infinite linear;
} 

@keyframes progres{
    0%{
      width: 0%;
    }
    25%{
        width: 50%;
    }
    50%{
        width: 75%;
    }
    75%{
        width: 85%;
    }
    100%{
        width: 100%;
    }
};
</style>
</head>
<body>
<div class="slide-progress-bar">
  <div class="progress-bar"></div>
</div>
</body>
</html>

设置间隔在页面最小化时停止。您可以使用 Date 对象来检查自进度条开始加载以来经过了多少时间。

<div class="slide-progress-bar">
  <div class="progress-bar" id="progress-bar"></div>
  <!--progress-bar-->
</div>
<script>
var animationTimeInMiliseconds = 30000; //30s 
var interval = 300;
var elem = document.getElementById("progress-bar");
var beginningDate = new Date().getTime(); // Time in miliseconds

function progressBar() {
  resetProgressBar();

  id = setInterval(frame, interval);

  function frame() {
  var milisecondsFromBegin = new Date().getTime() - beginningDate;
  var width = Math.floor(milisecondsFromBegin / animationTimeInMiliseconds * 100);
  elem.style.width = width + "%";

    if (width >= 100) {
      clearInterval(id);
    }
  }
}
function resetProgressBar() {

  elem.style.width = 0;
}
progressBar()
</script>
<style>
.slide-progress-bar {
  width: 150px;
  background-color:rgba(155, 155, 155, 0.36);
  transition: width 10s linear;
  display: inline-block;
  vertical-align: middle;
  margin: auto;
  width: 100%;
}

.progress-bar {
  height: 5px;
  background-color: #ff4546;
  position: relative;
  transition: linear;
}
</style>