<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> #con{height: 20px;width: 1px;background: #008000;text-align: center;color: #fff;} #btn{height: 20px;width: 40px;} </style> </head> <body> <div id="con"></div> <input type="submit" id="btn"value="點擊"/> <input type="submit" id="stop" value="中止"/> <div></div> </body> <script type="text/javascript"> var oBtn=document.getElementById("btn"); var oStop=document.getElementById("stop"); var oCon=document.getElementById("con"); var process=0; var timer=null;//和setTimeout()同樣,聲明timer用來關閉requestAnimationFrame()(請求動畫幀)的; var flag=false;//用來監視按鈕,防止在運動中受按鈕的重複影響 window.requestAnimationFrame=window.RequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame; window.cancelRequestAnimationFrame=window.CancelRequestAnimationFrame||window.webkitCancelRequestAnimationFrame||window.msCancelRequestAnimationFrame||window.mozCancelRequestAnimationFrame||window.oCancelRequestAnimationFrame; oBtn.addEventListener("click",function (){//添加時間委託,沒寫IE的兼容性 if(!flag){ timer=requestAnimationFrame(callback); } },false); oStop.addEventListener('click',function(){//添加時間委託 window.cancelRequestAnimationFrame(timer); flag=false; },false); function callback(){ process+=1;//缺點是若是這個數自加不會是100就會在小於100的最大倍數中止,如小數,3,7,等等 if(process<=100){ oCon.style.width=process+'%'; oCon.innerHTML=process+'%'; timer= requestAnimationFrame(callback);//用遞歸的方法來實現重複調用 } flag=true; } </script> </html>