JS动画封装

来源:互联网 发布:pp助手 mac 铃声制作 编辑:程序博客网 时间:2024/06/08 20:14

简单的运动函数

var demo1=document.getElementById("demo1");    demo1.onmouseover=function(){        startMove(0);    }    demo1.onmouseout=function(){        startMove(-320);    }var timer//全局变量function startMove(target){        clearInterval(timer)//一开始要清除所有的定时器避免累加改变速度        var demo1=document.getElementById("demo1");        timer=setInterval(function(){        //匀速运动        /*var speed=0;        if(demo1.offsetLeft>target){            speed=-10;        }else{            speed=10;        }*/        //变速运动        var speed=(target-demo1.offsetLeft)/10;//形成一个减速效果        speed=speed>0?Math.ceil(speed):Math.floor(speed)//进行取整,保证最后不会有剩余        if(demo1.offsetLeft==target){            clearInterval(timer);        }else{            demo1.style.left=demo1.offsetLeft+speed+'px';        }        },30)    }

效果图
这里写图片描述
第一张图实在鼠标经过时滑动出来的

图形变化和透明度变化JS代码

这个例子是一个同步运动var li=document.getElementById('li');    li.onmouseover=function(){        changeShape(li,{width:401,height:300,opacity:30});    }    li.onmouseout=function(){        changeShape(li,{width:400,height:200,opacity:100});//这里面的{}为json格式    }//changeShape(obj,{attr1:target1,attr2:target2},fn)function changeShape(obj,json,fn){    var flag=true;//假设所有运动到达目标值,确保不会有一个停止之后导致其他运动停止(同步运动)    clearInterval(obj.timer);    obj.timer=setInterval(function(){        for(attr in json){//这是json调取的格式,可以自行学习下        //这句话就是遍历其中属性            var cur=0;        if(attr=='opacity'){        //先变成浮点数,再进行四舍五入,因为数字变为浮点数时计算机无法准确取得,所以需要四舍五入            var cur=Math.round(parseFloat(getStyle(obj,attr))*100);        }else{            var cur=parseInt(getStyle(obj,attr))        }        //速度设定        var speed=(json[attr]-cur)/8;        speed=speed>0?Math.ceil(speed):Math.floor(speed);        //运动判断            if(cur!=json[attr]){            flag=false            }            if(attr=='opacity'){                obj.style.filter='alpha(opacity='+(cur+speed)+')'//兼容                obj.style.opacity=(cur+speed)/100;            }else{                obj.style[attr]=cur+speed+'px';            }           }        if(flag){            clearInterval(timer)            //回调函数,用来链式运动的,一个接着一个的运动            if(fn){                fn();            }        }    },30)}
0 0
原创粉丝点击