原生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>

 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值