不多說,直接上代碼
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>ProgressBar</title> 6 <style> 7 *{ 8 margin: 0; 9 padding: 0; 10 } 11 #progress{ 12 width: 100%; 13 height: 30px; 14 background: rgb(42, 138, 248); 15 } 16 #bar{ 17 width: 1%; 18 height: 28px; 19 margin-top: 1px; 20 background: purple; 21 } 22 23 </style> 24 25 </head> 26 <body> 27 <div id="progress"> 28 <div id="bar"></div> 29 </div> 30 <div><h3 id="text-progress">0%</h3></div> 31 <input type="button" id=“btn” value="點擊開始" onclick="action()"> 32 </body> 33 <script> 34 function action(){ 35 var iSpeed=1; 36 obj=setInterval(function(){ 37 iSpeed+=1; 38 if(iSpeed>=100){ // 設置達到多少進度后停止 39 clearInterval(obj); 40 } 41 bar.style.width=iSpeed+'%'; 42 document.getElementById('text-progress').innerHTML=iSpeed+'%'; 43 44 },100); // 1s后函數執行一次 45 } 46 </script> 47 </html>
結果
寫完之后發現有個bug,點擊開始后再次點擊進度條會再次執行
解決辦法:1、點擊開始后,將button的disabled設置為disabled,使不能再次點擊
2、添加判斷,給出message提示,如果進度條在進行中再次點擊給一個alter提示