主要用到的 offsetWidth 屬性,定時器。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>進度條 </title> 6 </head> 7 <style> 8 #progress{ 9 position: relative; 10 margin: auto; 11 top: 200px; 12 display: block; 13 width: 200px; 14 height: 20px; 15 border-style: dotted; 16 border-width: thin; 17 border-color: darkgreen; 18 } 19 #filldiv{ 20 position:absolute; 21 top: 0px; 22 left: 0px; 23 width: 0px; 24 height: 20px; 25 background: blue; 26 } 27 #percent{ 28 position: absolute; 29 top: 0px; 30 left: 200px; 31 } 32 </style> 33 <body> 34 <div id="progress"> 35 <div id="filldiv"></div> 36 <span id="percent">0</span> 37 </div> 38 </body> 39 </html> 40 <script type="text/javascript"> 41 //獲取所有需要的元素 42 var progress = document.getElementById("progress"); 43 var filldiv = document.getElementById("filldiv"); 44 var percent = document.getElementById("percent"); 45 46 var w = progress.clientWidth;//獲取整個進度條的長度 47 48 //開啟一個定時器 49 var timer = setInterval(function(){ 50 //filldiv的寬度遞增 51 //filldiv.offsetWidth,每一次獲取的都是當前的寬 52 filldiv.style.width = filldiv.offsetWidth + 1 + "px"; 53 //filldiv添加一個隨機背景顏色 54 filldiv.style.background = getColor(); 55 //percent統計百分比 56 percent.innerHTML = parseInt((filldiv.offsetWidth/w)*100) + "%"; 57 //當filldiv的寬到了200的寬就停止定時器 58 if(filldiv.offsetWidth == w){ 59 clearInterval(timer);//當進度達到100%時,關閉定時器,進度停止。 60 } 61 },10); 62 63 //獲取十六進制的隨機顏色值 64 function getColor(){ 65 var str = "0123456789abcdef"; 66 var color = "#"; 67 var rand; 68 //str有下標 0-15 69 //獲取0-15的隨機數 70 //通過這個隨機數作為str的下標, 71 //獲取隨機字符 72 //獲取六個隨機字符拼成一個字符串 73 for(var i = 0 ; i < 6 ;i++){ 74 rand = getRand(0,15); 75 color += str.charAt(rand); 76 } 77 return color; 78 } 79 80 //獲取min-max之間的隨機整數 81 function getRand(min,max){ 82 return parseInt(Math.random() * (max - min + 1) + min); 83 } 84 85 </script>
運行效果:

**可以將 getColor() 和 getRand() 函數放入一個公共的JS庫,下次使用時可以直接調用。