如何使用纯JavaScript在给定时间内增加或减少进度条宽度?

时间:2019-06-26 13:32:16

标签: javascript html css

  

我正在输入game,我的输入间隔为1秒   游戏已经存在,但我需要在UI中添加动画。它会在视觉上   向用户显示时间如何用完。

在这段代码中,我想在7秒内将进度条从0%增加到100%。虽然我实际上要减少

  

我该如何使用纯JavaScript?

时间在这里很重要,整个减少/增加过程应在我给定的时间内完成

function move() {
  var elem = document.getElementById("myBar");   
  var width = 0;
  var id = setInterval(frame, 1);
  // i want it to be done in 7 seconds
  var time = 7000;
  function frame() {
    if (width >= time) {
      clearInterval(id);
    } else {
      width++; 
      elem.style.width = (100*width)/time + '%'; 
      elem.innerHTML = Math.round((100*width)/time)  + '%';
    }
  }
}
#myProgress {
  width: 100%;
  background-color: #ddd;
}

#myBar {
  width: 0%;
  height: 30px;
  background-color: #4CAF50;
  text-align: center;
  line-height: 30px;
  color: white;
}
<!DOCTYPE html>
<html>
<body>
<div id="myProgress">
  <div id="myBar">0%</div>
</div>
<br>
<button onclick="move()">Start</button> 
</body>
</html>

2 个答案:

答案 0 :(得分:4)

我建议先使用requestAnimationFrame。接下来,使用计时器而不是计算它被调用了多少次。我做了一些小的调整(您可以用不同的数字来称呼它,以产生不同的延迟)。

RAF文档:https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

function move(delay) {
  var elem = document.getElementById("myBar");
  var end = Date.now() + delay;
  var frame = () => {
    var timeleft = Math.max(0, end - Date.now());
    elem.style.width = (100*timeleft)/delay + '%'; 
    elem.innerHTML = (timeleft/1000).toFixed(1)  + 's';
    if (timeleft === 0) return;
    requestAnimationFrame(frame);
  };
  requestAnimationFrame(frame);
}
#myProgress {
  width: 100%;
  background-color: #ddd;
}

#myBar {
  width: 100%;
  height: 30px;
  background-color: #4CAF50;
  text-align: center;
  line-height: 30px;
  color: white;
}
<!DOCTYPE html>
<html>
<body>
<div id="myProgress">
  <div id="myBar">7.0s</div>
</div>
<br>
<button onclick="move(7000)">Start</button> 
</body>
</html>

答案 1 :(得分:1)

喜欢吗?

function move() {
  var elem = document.getElementById("myBar");   
  var width = 0;
  var id = setInterval(frame, 1);
  // i want it to be done in 7 seconds
  var time = 7000;
  function frame() {
    if (width >= time) {
      clearInterval(id);
    } else {
      width++; 
      elem.style.width = 100-(100*width)/time + '%'; 
      elem.innerHTML = 100-Math.round((100*width)/time)  + '%';
    }
  }
}
#myProgress {
  width: 100%;
  background-color: #ddd;
}

#myBar {
  width: 100%;
  height: 30px;
  background-color: #4CAF50;
  text-align: center;
  line-height: 30px;
  color: white;
}
<!DOCTYPE html>
<html>
<body>
<div id="myProgress">
  <div id="myBar">100%</div>
</div>
<br>
<button onclick="move()">Start</button> 
</body>
</html>