首先此函数是基于大家都知道的Tween动画算法的,在此基础上使用了三中讲到的兼容版动画贞,可以使动画变得更流畅。
1. 首先要记得引入Tween.js
2. 引入mTween.js
3. 调用
* mTwee.js文件如下: (这里的m意为mobile)
(function(){ window.requestAnimationFrame = window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame; window.cancelAnimationFrame = window.cancelAnimationFrame|| window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame||window.cancelRequestAnimationFrame||window.webkitCancelRequestAnimationFrame||window.mozCancelRequestAnimationFrame; if(!requestAnimationFrame){ var lastTime = Date.now(); window.requestAnimationFrame = function(callback){ var id; var nowTime = Date.now(); var delay = Math.max(16.7-(nowTime-lastTime),0); id = setTimeout(callback,delay); lastTime = nowTime + delay; return id; }; } if(!cancelAnimationFrame){ window.cancelAnimationFrame = function(index){ clearTimeout(index); }; } })(); function transform(el,attr,val){ if(!el.transform){ el.transform = { }; } if(val === undefined){ return el.transform[attr]; } el.transform[attr] = val; var str = ""; for(var s in el.transform){ switch(s){ case "rotate": case "rotateX": case "rotateY": case "rotateZ": case "skewX": case "skewY": str += s +"("+el.transform[s]+"deg) "; break; case "scale": case "scaleX": case "scaleY": str += s +"("+el.transform[s]+") "; break; case "translateX": case "translateY": case "translateZ": str += s +"("+el.transform[s]+"px) "; break; } } el.style.WebkitTransform = el.style.transform = str; } function css(el,attr,val){ var transformAttr = ["rotate","rotateX","rotateY","rotateZ","skewX","skewY","scale","scaleX","scaleY","translateX","translateY","translateZ"]; for(var i = 0; i < transformAttr.length; i++){ if(attr == transformAttr[i]){ return transform(el,attr,val); } } if(val === undefined){ val = getComputedStyle(el)[attr]; console.log(val); val = parseFloat(val); return val; } if(attr == "opacity"){ el.style[attr] = val; } else { el.style[attr] = val + "px"; } } function mTween(init){ var t = 0; var b = {}; var c = {}; var d = Math.ceil(init.time/16.7); cancelAnimationFrame(init.el.timer); for(var s in init.target) { b[s] = css(init.el,s); c[s] = init.target[s] - b[s]; } init.el.timer = requestAnimationFrame(move); function move(){ if(t > d){ cancelAnimationFrame(init.el.timer); init.callBack&&init.callBack.call(init.el); } else { t++; for(var s in init.target){ var val = Tween[init.type](t,b[s],c[s],d); css(init.el,s,val); } init.callIn&&init.callIn.call(init.el); init.el.timer = requestAnimationFrame(move); } } }
调用方法:
var box = document.querySelector(‘#box‘); css(box,"translateX",0); css(box,"translateY",0); mTween({ el: box, type: "elasticIn", time: 1000, target: { translateX: 200, translateY: 400 }, callBack: function(){ console.log("动画执行完了"); }, callIn: function(){ console.log("动画执行中"); } });