我移动端一般就是用css3的动画,pc端都是用jq那几个常用动画就没用过其他的了,想问下大家用原生js实现运动效果都是怎么实现的?会不会很麻烦或者用什么库吗?
1 回答
POPMUISE
TA贡献1765条经验 获得超5个赞
一般是:
setInterval(function(){ //dosomething...},1000/60);
或者:
window.requestAnimationFrame(function(/* time */ time){ // time ~= +new Date // the unix time});
或者:
// shim layer with setTimeout fallbackwindow.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })();// usage:// instead of setInterval(render, 16) ....(function animloop(){ requestAnimFrame(animloop); render(); })();// place the rAF *before* the render() to assure as close to// 60fps with the setTimeout fallback.
或者(更牢靠的封装
):
(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'] || 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); }; }());
添加回答
举报
0/150
提交
取消