编写一份js的运动函数,为了以后方便查阅

var t=document.getElementById("t");
        var d=document.getElementById("d");
        var t1=document.getElementById("t1");
        function getArr(){
            arr=[];
            for(var i=16;i>0;i-=2){
                arr.push(-i);
                arr.push(i);
            }
                arr.push(0);
                return arr;
        }
        t1.onmouseover=function(){
            this.style.cursor="pointer";
            doMove(t1,"top",getArr(),20,-130,200);
        }
        d.onclick=function(){
            if(!t.index){ //undefined==false的结果是false
                doMove(t,"left",10,20,-0);
                t.index=true;
            }else{
                doMove(t,"left",-10,20,-130);
                t.index=false;
            }
                //console.log(t.index);
        }
        /* e是元素,s是元素的属性,p是元素运动的步长,(可以是同一速度就传递一个数.不同的速度可以传递一个数组)
        h是元素运动的频率,t是目标点,fun是回调函数
        此函数可以省略最后两个参数,这样的话就没有原始位置
        tl参数是确定元素的初识位置,防止不在原来的位置
        */
        /*使用此函数要事先手动指定元素的位置.
     此函数只能改变带有px单位的元素.如颜色的改变不适合本函数 */
        function doMove(e,s,p,h,t,tl,fun){
            clearInterval(e.timer);
            var i=0;
            if(tl==0||tl){
                e.style[s]=tl+'px';//防止抖动的时候脱离原来的位置.所以先要确定初始位置
            }
            
            e.timer=setInterval(function(){
                var d=p instanceof Array?p[i]:p;//判断传的步长是数组还是数字
                i++;
                var speed=parseInt(getStyle(e,s))+d;
                if((t||t==0)&&speed>t&&p>0){//注意这里当目标点为0的时候js自动将其转化为false
                    speed=t;
                }
                if((t||t==0)&&speed<t&&p<0){
                    speed=t;
                }
                e.style[s]=speed+"px";
                if((t||t==0)&&speed==t ||i==p.length&& p instanceof Array){
                    clearInterval(e.timer);
                    fun && fun();//函数执行完后要执行的函数
                }
            },h);
        }
        function getStyle(e,s){
            return e.currentStyle?e.currentStyle[s]:getComputedStyle(e)[s];
            }
<div id="t">
        <div id="d">分享</div>
    </div>
    <div id="t1">    
    </div>
*{margin: 0px;padding: 0px;}
        #t{width: 130px;height: 130px;background: red;position: absolute;
                left: -130px;top: 200px;
            }
        #d{width: 30px;height: 50px;background: black;position: absolute;left: 130px;top: 35px;color: white;text-align: center;cursor:pointer;}
        #t1{width: 130px;height: 130px;background: green;position: absolute;left: 300px;top: 200px;
                
            }
 /*使用此函数要事先手动指定元素的位置.*/
一生的日子很长,一定要注意调节,要劳逸结合
原文地址:https://www.cnblogs.com/weikemudan/p/10286173.html