原生Js缓动动画封装过程及注释

效果图:

原生Js缓动动画封装过程及注释

源代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        #box{
            width: 300px;
            height: 300px;
            background-color:orange;
            border-radius:50%;
            position:absolute;
        }
        button{
            padding:5px 10px;
            margin-top:100px;
        }
    </style>
</head>
<body>
<button>0</button>
<button>600</button>
<button>1200</button>
<div id="box"></div>
<script>
    var box=document.getElementById("box");
    var btns=document.getElementsByTagName("button");
    btns[0].onclick=function(){
        constant_speed_X(box,0)
    };
    btns[1].onclick=function(){
        constant_speed_X(box,700)
    };
    btns[2].onclick=function(){
        constant_speed_X(box,1400)
    };
    function constant_speed_X(ele,endX){
        //1.要用定时器先清除定时器
        clearInterval(ele.timer);
       //2.启动定时器
         ele.timer=setInterval(function(){
             //3.先获取步长,此时获取的补偿越来越小
             var step=(endX-ele.offsetLeft)/10;
            // 4.步长二次加工,当步长大于零时向下取整,否则相反
             step=step>0?Math.ceil(step):Math.floor(step);
            //5.位移元素
            ele.style.left=ele.offsetLeft+step+"px";
            //6.判断停止定时器,当终点位置与当前位置的距离的绝对值小于一个步长就停止定时器
            if(Math.abs(endX-ele.offsetLeft)<=Math.abs(step)){
                clearInterval(ele.timer);
                //7.剩下小于一个步长的距离直接通过闪动动画拉到终点位置
                ele.style.left=endX+"px";
            }
        },30)
    }
</script>
</body>
</html>