这两天在慕课网学习了一门课程即Js动画效果,循序渐进的做一个运动框架。可以实现多物体的同时运动,链式运动。
运动框架 move.js
1 //startMove(obj,{attr1:itarget1,attr2:itarget2},fn) 2 function startMove(obj,json,fn){ 3 4 clearInterval(obj.timer) 5 obj.timer = setInterval(function(){ 6 var flag = true;//假设所有都到达目标值 7 for(var attr in json){ 8 9 //取当前值10 var icur = 0;11 if(attr == 'opacity'){12 icur = Math.round(parseFloat(getStyle(obj,attr)) * 100 );13 }14 else{15 icur = parseInt(getStyle(obj,attr));16 }17 18 //定义速度19 var speed = (json[attr] - icur)/8;20 speed = speed > 0?Math.ceil(speed):Math.floor(speed);21 22 //判断是否停止23 if(json[attr] != icur){24 flag = false;25 }26 if(attr == 'opacity'){27 obj.style.filter = 'alpha(opacity:'+(icur + speed)+')';28 obj.style.opacity = (icur + speed)/100;29 }30 else{31 obj.style[attr] = icur + speed + 'px';32 }33 }//json for-in34 35 //在所有属性都到达目标值后,判断是否有回调函数(链式动画)36 if(flag){37 clearInterval(obj.timer);38 if(fn){39 fn();40 };41 }42 },30)43 }44 45 function getStyle(obj,attr){//解决加了边框之后bug46 if(obj.currentStyle){47 return obj,currentStyle[attr];48 }49 else{50 return getComputedStyle(obj,false)[attr];51 }52 }
引用move.js的格式
1 2 3 4 5jsonmove 6 36 84 85
慕课网JS动画效果-http://www.imooc.com/learn/167
代码演示地址:http://runjs.cn/detail/2jhz4bmc