js运动框架


原生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];//火狐
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值