如何在某一点停止JavaScript进度条

时间:2017-01-19 22:05:59

标签: javascript html css progress

我正在使用W3Schools.com中显示的示例进度条。

如何让进度条停在固定点,比方说,90%?我看到它与条的宽度有关,但我无法弄清楚如何将它改为固定点,甚至变量。

function move() {
  var elem = document.getElementById("myBar");
  var width = 10;
  var id = setInterval(frame, 10);

  function frame() {
    if (width >= 100) {
      clearInterval(id);
    } else {
      width++;
      elem.style.width = width + '%';
      document.getElementById("label").innerHTML = width * 1 + '%';
    }
  }
}
#myProgress {
  position: relative;
  width: 100%;
  height: 30px;
  background-color: #ddd;
}
#myBar {
  position: absolute;
  width: 10%;
  height: 100%;
  background-color: #4CAF50;
}
#label {
  text-align: center;
  line-height: 30px;
  color: white;
}
<h1>JavaScript Progress Bar</h1>

<div id="myProgress">
  <div id="myBar">
    <div id="label">10%</div>
  </div>
</div>

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

1 个答案:

答案 0 :(得分:0)

将条件更改为width >= 90

代码:

function move() {
  var elem = document.getElementById("myBar");   
  var width = 10;
  var id = setInterval(frame, 10);
  function frame() {
    /* CHANGE THIS TO 90 */
    if (width >= 90) {
      clearInterval(id);
    } else {
      width++; 
      elem.style.width = width + '%'; 
      document.getElementById("label").innerHTML = width * 1  + '%';
    }
  }
}

工作样本:https://jsfiddle.net/mspinks/vLfhno9x/