SOURCE

console 命令行工具 X clear

                    
>
console
window.onload=function(){
    var btn1=document.getElementById("btn1");
    var div1=document.getElementById("div1");
    btn1.onclick=function(){
        move(div1,"left",1,100,function(){
            move(div1,"left",1,0);
        });

    };
};
//升旗代码提取为的函数
//obj参数:为要应用的元素
//attr参数:比如获取left,width等属性
//speed参数:样式移动的速度
//target参数:移动到的目标位置
//callback参数:回调函数
function move(obj,attr,speed,target,callback){
    //将当前对象里面的定时器返回值作为参数
    clearInterval(obj.timer);
    //定时器将返回值存在当前对象里面
    obj.timer=setInterval(function(){
        //获取当前元素指定样式值
        var oldvalue=parseInt(getComputedStyle(obj,null)[attr]);
        //判断速度的正负值,当前位置大于目标位置就说明要往小了移动
        if(speed>target)
            speed=-speed;
        var newvalue=oldvalue+speed;
        //判断移动是左或右
        //当前位置大于目标位置并且移动大于0,说明现在超出设置的位置了
        //当前位置小于目标位置并且移动小于0,同理,需要设置为目标位置
        if((newvalue>target&&speed>0)||(speed<0&&newvalue<target))
            newvalue=target;
        obj.style[attr]=newvalue+"px";
        if(newvalue==target)
        {
            clearInterval(obj.timer);
            callback&&callback();
        }

    },30)
}
<button id="btn1">变化</button><br/><br/>
<div id="div1"></div>
<div style="height:265px;position:absolute;border-left:1px yellow solid;left:100px"></div>
#div1{
    width:50px;
    height:50px;
    background-color:red;
    position:absolute;
}