js运动框架
2016-12-26 14:56
411 查看
原生js实现动画运动,对象单个运动(移动,改变width,改变height–) 多对象运动,链式运动(先变width再变height);同时运动(width和height同时变化) 有什么错误欢迎指出来
使用方法:
运动框架源码:
使用方法:
var div=document.getElementById("div"); div.onmouseover=function(){ startMove(div,{width:300},function(){//将宽度变为300px alert("完成"); } }
运动框架源码:
//element是对象,json是js对象,你要操作的属性和数值,fn是回调函数 function startMove(element,json,fn){ var flag=null;//是否执行完操作的标志 clearInterval(element.timer);//每次开始清除定时器 element.timer=setInterval(function(){ flag=true; for(var attr in json){//将js对象遍历--attr为属性,json[attr]为值; //取当前值 var curent=0; if(attr=='opacity'){//透明度动画 curent=Math.round(parseFloat(getStyle(element,attr))*100); }else{//其他运动 curent=parseInt(getStyle(element,attr)); } //计算速度 var speed=(json[attr]-curent)/40; //ceil是向下取整,floor是向上取整 既Math.ceil(0.4)==1;Math.floor(0.4)==0; speed=speed>0?Math.ceil(speed):Math.floor(speed); console.log("speed"+speed); //检测停止 if(curent!=json[attr]){ flag=false;//如果没有所有运动都完成,就不会停止; if (attr=='opacity') { element.style.filter='alpha(opacity:'+(curent+speed)+')';//兼容ie element.style.opacity=(curent+speed)/100; }else{ element.style[attr]=curent+speed+'px'; } } } if (flag){//全部运动完成 停止计时器并执行回掉函数 clearInterval(element.timer); if (fn){ fn(); } } }) } function getStyle(element,attr){//获取样式 if(element.currentStyle){ return element.currentStyle[attr];//ie }else{ return getComputedStyle(element,false)[attr];//火狐 } }