只是在项目中尝试着代替了interval,据说效果比较好。先记录下。
代码片段:
var nextFrame=(function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(callback){ return setTimeout(callback , 1);};
})();
function doClose(){
var animationFlag=true;
var nowLeft=0;
var nowRight=rightWidth;
var timer=function(){
if(nowLeft -everyChangeWidth>-1*leftWidth){
nowLeft-=everyChangeWidth;
nowRight+=everyChangeWidth;
left.style.left=nowLeft+"px";
right.style.width=nowRight+"px";
}else{
nowLeft=-1*leftWidth;
nowRight=leftWidth+rightWidth;
animationFlag=false;
left.style.visibility="hidden";
showbar.style.display="block";
left.style.left=nowLeft+"px";
right.style.width="100%";
return;
}
browseListView.resize();
if(animationFlag) nextFrame(timer);
};
timer();
}
原来:
function doClose(){
var nowLeft=0;
var nowRight=rightWidth;
var timer=setInterval(function(){
if(nowLeft -everyChangeWidth>-1*leftWidth){
nowLeft-=everyChangeWidth;
nowRight+=everyChangeWidth;
left.style.left=nowLeft+"px";
right.style.width=nowRight+"px";
}else{
nowLeft=-1*leftWidth;
nowRight=leftWidth+rightWidth;
clearInterval(timer);
left.style.visibility="hidden";
showbar.style.display="block";
left.style.left=nowLeft+"px";
right.style.width="100%";
return;
}
listView1.resize();
},timerValue);
}
优势:
- 对于一个侦中对DOM的所有操作,只进行一次Layout和Paint。
- 如果发生动画的元素被隐藏了,那么就不再去Paint。
使用方法:
- 调用requestAnimationFrame函数,传递一个callback参数,则在下一个动画帧时,会调用callback。
- 不传递参数地直接调用该函数,启动动画帧,下一个帧触发时,会同时触发window.onmozbeforepaint事件,可以通过注册该事件来进行动画。
第2种方法由于依赖于Firefox自己的事件,且beforepaint事件还没进入到标准中,所以不推荐使用,还是使用第1种方式比较好。此时,我们的动画逻辑可以变成这样:
- 记录当前时间startTime,作为动画开始的时间。
- 请求下一帧,带上回调函数。
- 下一帧触发时,回调函数的第一个参数为当前的时间,再与startTime进行比较,确定时间间隔ellapseTime。
- 判断ellapseTime是否已经超过事先设定的动画时间time,如果超过,则结束动画。
- 计算动画属性变化的差值differ = to – from,再确定在ellapseTime的时候应该变化多少step = differ / time * ellapseTime。
- 计算出现在应该变化到的位置Math.round(from + step),并重新对样式赋值。
- 继续请求下一帧。
摘自:http://www.cnblogs.com/rubylouvre/archive/2011/08/22/2148797.html