requestAnimationFrame 实现JS动画
requestAnimationFrame会随着浏览器绘制窗口的频率来绘制动画以达到最好的用户体验
// let raf = (function(){
// return window.requestAnimationFrame ||
// window.webkitRequestAnimationFrame ||
// window.mozRequestAnimationFrame ||
// function( callback ){
// window.setTimeout(callback, 1000 / 60);//每秒实现60帧的动画效果最好
// };
// })();
let raf = window.requestAnimationFrame;
let box = document.getElementsByClassName('box')[0];
let w = 100;
let t = 0;
function loop(){
box.style.width = w + 'px';
if(w < 500){
w += 1;
box.style.width = w + 'px';
}
t = raf(loop)
}
loop()
box.addEventListener('click',()=>{//实现点击暂停动画,再次点击继续运行的效果
if(t){
window.cancelAnimationFrame(t);
t = 0;
}else{
t = raf(loop)
}
})