如何降低装卸杆的速度?

时间:2019-02-28 10:40:50

标签: javascript jquery html css

我想制作一个持续7秒的自定义加载栏动画。我已经使用javascript创建了以下代码,但是它的运行速度比我预期的要快。持续7秒的正确方法是什么?

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

  function frame() {
    if (width >= 100) {
      clearInterval(id);
    } else {
      width++;
      elem.style.width = width + '%';
      elem.innerHTML = width * 1 + '%';
    }
  }
}
#myProgress {
  width: 100%;
  background-color: grey;
  border-radius: 6px;
}

#myBar {
  width: 10%;
  height: 30px;
  background-color: #4CAF50;
  text-align: center;
  /* To center it horizontally (if you want) */
  line-height: 30px;
  /* To center it vertically */
  color: white;
  border-radius: 6px;
}
<div style="width:200px;align:left;text-align:left;border-radius:6px;">
  <div id="myProgress">
    <div id="myBar">1%</div>
  </div>
</div>

<button value="run" onclick="move()">RUN</button>

演示https://codepen.io/anon/pen/zbvzgL

3 个答案:

答案 0 :(得分:3)

timeout时间设置为更大的值,因为setTimeout函数中的时间以 ms 为单位, 1ms 很小时间间隔。根据需要的速度尝试 10ms 100ms

setInterval(frame, 100);

function move() {
  var elem = document.getElementById("myBar");
  var width = 2;
  var id = setInterval(frame, 100);
  function frame() {
    if (width >= 100) {
      clearInterval(id);
    } else {
      width++;
      elem.style.width = width + '%';
      elem.innerHTML = width * 1 + '%';
    }
  }
}
#myProgress {
  width: 100%;
  background-color: grey;
border-radius:6px;
}

#myBar {
  width: 10%;
  height: 30px;
  background-color: #4CAF50;
  text-align: center; /* To center it horizontally (if you want) */
  line-height: 30px; /* To center it vertically */
  color: white;
border-radius:6px;
}
<div style="width:200px;align:left;text-align:left;border-radius:6px;">
<div id="myProgress">
  <div id="myBar">1%</div>
</div>
</div>

<button value="run" onclick="move()">RUN</button>

答案 1 :(得分:1)

如果显示加载百分比是可选的,则可以使用CSS来完成此操作。 CSS动画将永远比JS动画快。

function move() {
  var elem = document.getElementById("myBar");
  elem.innerText = "Loading...";
  elem.classList.add('slow');
  setTimeout(function() { elem.innerText = "Loading Completed"; }, 7000)
}
#myProgress {
  width: 100%;
  background-color: grey;
  border-radius: 6px;
}

#myBar {
  width: 0%;
  height: 30px;
  background-color: #4CAF50;
  text-align: center;
  /* To center it horizontally (if you want) */
  line-height: 30px;
  /* To center it vertically */
  color: white;
  border-radius: 6px;
}

#myBar.slow {
  width: 100%;
  transition: 7000ms;
}
<div style="width:200px;align:left;text-align:left;border-radius:6px;">
  <div id="myProgress">
    <div id="myBar"></div>
  </div>
</div>

<button value="run" onclick="move()">RUN</button>

答案 2 :(得分:1)

您需要更改setInterval值,例如->

var id = setInterval(frame, 15);

如果您想要7秒70或60秒,就足够了。

var id = setInterval(frame, 60);