基于RAF的一个小动画框

RAF也即是requestAnimationFrame,之前的动画都是基于setTimeout写的,所以为了性能方面的考虑,开始使用requestAnimationFrame写动画。

function animation(obj, data) {
    if (obj.timer) {
        window.cancelAnimationFrame(obj.timer)
    }
    obj.timer = window.requestAnimationFrame(function () {
        for (var i in data) {
            var current=parseInt(obj.style[i]);
            var target=parseInt(data[i]);
            var speed=(target-current)/8;
            speed=speed>0?Math.ceil(speed):Math.floor(speed);

            if(current!=target){
                obj.style[i]=current+speed+"px";
                obj.timer=window.requestAnimationFrame(arguments.callee);
            }
        }
    })
}
原文地址:https://www.cnblogs.com/jelly7723/p/5513782.html