requestAnimationFrame实现动画

requestAnimFrame兼容文件

window.requestAnimFrame = (function() {
    var lastTime = 0;
    var vendors = ['webkit', 'moz'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] ||    // Webkit中此取消方法的名字变了
                                      window[vendors[x] + 'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame) {
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16.7 - (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);
        };
    }
}());

进度条例子

<!-- html 结构 -->
<div id="test" style="width:1px;height:17px;background:#0f0;">0%</div>

// js代码
先引入上面的requestAnimationFrame兼容处理js文件

var start = null;
var ele = document.getElementById("test");
var progress = 0;

function step(timestamp) {
progress += 1;
ele.style.width = progress + "%";
ele.innerHTML = progress + "%";
if(progress < 100) {
    requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
document.getElementById("run").addEventListener("click", function() {
ele.style.width = "1px";
progress = 0;
requestAnimationFrame(step);
}, false);

参考

猜你喜欢

转载自www.cnblogs.com/bonly-ge/p/10184324.html