我使用width功能将进度条从setInterval 100减少到0。因此,基本上我的宽度每20ms从1开始减小。然后,当width到达0时,我将width设置为100以再次运行进度栏。在每个循环中,我都会更改进度栏中的文本。我现在想做的是更改每个循环的时间间隔(20毫秒)。

Si在我的代码中,当我从1增加时,我的20被替换为interval[i] ...但是我将setInterval放入循环中...

下面的代码可在每个循环中更改文本,但不知道如何改进它以在每次i迭代时更改时间间隔。



function move() {
  var message = ['test', 'test2', 'test3'];
  var interval = [10, 20, 30]
  var elem = document.getElementById("myBar");

  var width = 100;
  var i = 0;

  var id = setInterval(frame, 20);

  function frame() {

    width = width - 1;
    elem.style.width = width + "%";
    elem.textContent = message[i];
    if (width == 0 && i < 3) {
      width = 100;
      i++;
    }
    if (i == 3) {
      clearInterval(id);
    }
  }
}

#myProgress {
  width: 100%;
  background-color: #ddd;
}

#myBar {
  width: 100%;
  height: 30px;
  background-color: #4CAF50;
}

<h1>JavaScript Progress Bar</h1>

<div id="myProgress">
  <div id="myBar"> </div>
</div>

<br>
<button onclick="move()">Click Me</button>

最佳答案

<html>
<style>
#myProgress {
  width: 100%;
  background-color: #ddd;
}

#myBar {
  width: 100%;
  height: 30px;
  background-color: #4CAF50;
}
</style>
<body>

<h1>JavaScript Progress Bar</h1>

<div id="myProgress">
  <div id="myBar"> </div>
</div>

<br>
<button onclick="move()">Click Me</button>

<script>

function move() {
        var message = ['test','test2','test3'];
        var interval = [10,20,30]
        var elem = document.getElementById("myBar");

        var width = 100;
        var i = 0;


        var id = setInterval(frame, interval[i]);

      function frame() {

          width = width - 1;
          elem.style.width = width + "%";
          elem.textContent = message[i];
          if (width == 0 && i < 3) {
            width = 100;
            i++;
            clearInterval(id);
            id = setInterval(frame, interval[i]);
          }

          if (i == 3) {
            clearInterval(id);
          }
        }

      }

</script>

</body>
</html>

关于javascript - 运行进度条,每个循环的时间间隔都在变化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60561301/

10-12 12:39
查看更多