requestAnimationFrame可以用来解决循环等代码执行时间长,造成浏览器阻塞页面的渲染的问题。
基本使用方法如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{margin: 0;padding: 0;}
#container{
background-color: #bfbfbf;
width: 800px;
height: 300px;
}
#scene{
margin: 10px;
}
img{
display: block;
width: 0;
height: 0;
}
</style>
</head>
<body>
<div id="scene">
<img src="./link.jpg" alt="the img can't be displayed rightly" id="img">
<hr/>
<button id="btn1">show</button>
<button id="btn2">hidden</button>
</div>
<script>
window.onload = function() {
btn1.onclick = function() {
img.style.width = '0';
img.style.height = '0';
var flag = requestAnimationFrame(function f1(){
if(img.width < 374){
img.style.width = parseInt(img.style.width) + 374/100 + "px";
img.style.height = parseInt(img.style.height) + 250/100 + "px";
flag = requestAnimationFrame(f1);
}
else
cancelAnimationFrame(flag);
});
}
btn2.onclick = function() {
if(img.width >= 0){
var flag = requestAnimationFrame(function f2(){
if(img.width > 0){
img.style.width = parseInt(img.style.width) - 374/100 + "px";
img.style.height = parseInt(img.style.height) - 250/100 + "px";
if(Math.abs(img.width - 374/100)<1){
img.style.width = '0';
img.style.height = '0';
}
flag = requestAnimationFrame(f2);
}
else
cancelAnimationFrame(flag);
});
}
}
}
</script>
</body>
</html>
由于requestAnimationFrame并不是支持所有的浏览器(具体可以参考caniuse),考虑到通用性,有了requestAnimationFrame Polyfill的诞生,此处给出具体实现:
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
// MIT license
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
|| window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
它主要是在不兼容requestAnimationFrame时借助setTimeout实现了该功能。更多关于requestAnimationFrame的详情可以参考此处