Javascript Progess栏无法正确加载

时间:2017-03-27 02:54:36

标签: javascript jquery progress-bar loading

我正在开发一个简单的jquery加载栏,我可以将其发布到。我的问题是它似乎只跳转到最后的结果,即使在javascript中设置了settimeout。

测试脚本包括3个完美工作的按钮,但是我需要能够从底部的内联代码调用该函数。这似乎会跳到最后的结果75%而没有显示25%和等待3秒,正如我所希望的那样。

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

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

<h1>Progress Bar</h1>

<div id="Progress">
  <div id="Bar" style="width:0px;"></div>
</div>

<br>
Buttons for testing bar not needed in actual script<br>
<button onclick="move(50)">Test Bar 50%</button> <br>
<button onclick="move(75)">Test Bar 75%</button> <br>
<button onclick="move(100)">Test Bar 100%</button> <br>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script>
function move(amount) {
  var elem = document.getElementById("Bar");   
  elem.style.width = amount + '%'; 
}
// Inline calls I need to use for my script. These seem to jump to the last one when loaded dispite timeout.
setTimeout(function(){
  move(25);
}, 3000);
setTimeout(function(){
  move(75);
}, 3000);
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

目前,两个setTimeout调用并行运行,因此在完成时您只看到75%的结果(即使25%的结果发生,它也不再可见)。

您可以嵌套setTimeout次呼叫,以便它们按顺序执行。请参阅下面的代码:

function move(amount) {
  var elem = document.getElementById("Bar");
  elem.style.width = amount + '%';
}
// nest the setTimeout calls so they fire sequentially
setTimeout(function() {
  move(25);
  setTimeout(function() {
    move(75);
  }, 3000);
}, 3000);
#Progress {
  width: 100%;
  background-color: #ddd;
}

#Bar {
  width: 1%;
  height: 30px;
  background-color: #4CAF50;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Progress">
  <div id="Bar" style="width:0px;"></div>
</div>

<br> Buttons for testing bar not needed in actual script<br>
<button onclick="move(50)">Test Bar 50%</button> <br>
<button onclick="move(75)">Test Bar 75%</button> <br>
<button onclick="move(100)">Test Bar 100%</button> <br>

更新

如果要显示可变数量的进度点,则可以使用下面根据此useful answer改编的技术。

function move(amount) {
  var elem = document.getElementById("Bar");
  elem.style.width = amount + '%';
}

// set array of points:
var movements = [10, 20, 30, 50, 75, 99, 100];
var i = -1;

function moveSequence() {
  move(movements[i++]);
  if (i < movements.length) setTimeout(moveSequence, 1000);
}
moveSequence();
#Progress {
  width: 100%;
  background-color: #ddd;
}

#Bar {
  width: 1%;
  height: 30px;
  background-color: #4CAF50;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Progress">
  <div id="Bar" style="width:0px;"></div>
</div>

<br> Buttons for testing bar not needed in actual script<br>
<button onclick="move(50)">Test Bar 50%</button> <br>
<button onclick="move(75)">Test Bar 75%</button> <br>
<button onclick="move(100)">Test Bar 100%</button> <br>