Tween.js各种曲线运动
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>变速运动</title> <style type="text/css"> *{ margin: 0; padding: 0; } #box{ width: 100px; height: 100px; background: red; position: absolute; top: 0px; left: 0px; opacity: 1; filter: alpha(opacity=100); } </style> </head> <body> <script src="js/Tween.js" type="text/javascript" charset="utf-8"></script> <div id="box"></div> <script type="text/javascript"> var oBox = document.getElementById("box"); //调用函数,传参 animate( oBox , {'width':300,'height':250,'top':300,'left':200,'opacity':0.4} , 2000 , 'linear' ,function(){ animate( oBox , {'width':100,'height':50,'top':100,'left':100,'opacity':0.8} , 2000 , 'linear'); } ); function animate( obj , Json , time , ev , fn ){ //判断缺省参数,最好把参数都放到一个json中,可以随意传参 if( typeof time == 'undefined' ) { time = 1000; ev = 'linear'; } else if( typeof time == 'string' ) { fn = ev; ev = time; time = 1000; } else if( typeof ev == 'function' ) { fn = ev; ev = 'linear'; } else if( typeof time == 'function' ) { fn = time; ev = 'linear'; time = 1000; } ev = ev || event; //定义一个json oB来存储运动前的初始状态下的属性值,即运动的初始位置 var oB = {}; for( attr in Json ) { oB[attr] = parseInt( getStyle( obj , attr ) ); } //定义一个json oC来存储运动结束位置与当前位置的差值 var oC = {}; for( attr in Json ) { oC[attr] = Json[attr] - parseInt( getStyle( obj , attr ) ); } //获取当前开始时间 var startTime = new Date().getTime(); clearInterval(obj.timer); //定时器,控制运动时间,时间到,清除 obj.timer = setInterval( function(){ //获取当前时间 var nowTime = new Date().getTime(); //获取运动过程的时间,如果超过设置的运动时间就停止 var oT = Math.min( nowTime - startTime , time ); //获取需要运动的每个属性 for( attr in Json ) { //属性为透明度时 if( attr == 'opacity' ) { var iCon = Tween[ ev ]( oT , oB[attr] , oC[attr] , time ); if( isNaN( iCon ) ){ iCon = 1; }; obj.style.opacity = iCon; obj.style.filter = 'alpha(opacity = '+parseInt( (iCon*100) )+')'; } //属性不为透明度时 else{ obj.style[attr] = Tween[ ev ]( oT , oB[attr] , oC[attr] , time ) + 'px'; } } //设置时间到,清除定时器,执行回调函数 if( oT == time ) { clearInterval( obj.timer ); fn && fn(); } },30 ) } //兼容获取属性的属性值 function getStyle( obj , attr ){ return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle( obj , false )[attr]; } </script> </body> </html>