js百分比載入進度條效果

admin發表於2017-04-16

分享一段程式碼例項,它實現了載入進度條效果。

資料能夠實時變化,並且進度條以百分比顯示,程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
.box {
  width: 1200px;
  margin: 100px auto;
}
.div1 {
  height: 20px;
  width: 100px;
  border: 1px solid gray;
  padding: 2px;
}
#div2 {
  height: 20px;
  width: 0;
  background-color: green;
  position: absolute;
}
</style>
<script>
var timer=null;
var width=0;
 
function start(){
  timer = setTimeout(onChange, 10);
}
function stop(){
  clearInterval(timer);
}
function onChange(){
  if(width==100){
    window.clearInterval(timer);
  }else{
    width+=1;
    document.getElementById("div2").style.width=width+"px";
    document.getElementById("div2").innerHTML=Math.round(width)+"%";
    timer=setTimeout(onChange,100);
  }
}
window.onload = function () {
  var ostart = document.getElementById("start");
  var ostop = document.getElementById("stop");
  ostart.onclick = function () {
    start()
  }
  ostop.onclick = function () {
    stop()
  }
}
</script>
</head>
<body>
  <div class="box">
    <div class="div1">
      <div id="div2"></div>
    </div>
    <br />
    <input id="start" type="button" value="開始" />
    <input id="stop" type="button" value="停止"  />
  </div>
</body>
</html>

相關文章