<!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>