缓动动画(速度由快转慢)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            position: absolute;
            top: 50px;
            left: 0;
            width: 105px;
            height: 105px;
            padding: 5px;
            background: pink;
        }

        .box1,
        .box2,
        .box3,
        .box4 {
            float: left;
            width: 50px;
            height: 50px;
            border: 1px solid black;
        }

        .box1 {
            background: rgb(239, 163, 163);
        }

        .box2 {
            background: rgb(186, 247, 155);
        }

        .box3 {
            background: rgb(155, 233, 247);
        }

        .box4 {
            background: rgb(155, 155, 247);
        }
    </style>
</head>

<body>
    <button>移动到1000</button>
    <button>移动到500</button>
    <div class="box">
        <div class="box1"></div>
        <div class="box2"></div>
        <div class="box3"></div>
        <div class="box4"></div>
    </div>


    <script>
        // 获取页面元素
        var box = document.querySelector('.box');
        var btn = document.querySelectorAll('button');

        btn[0].onclick = function () {
            fn(box, 1000)
        }
        btn[1].onclick = function () {
            fn(box, 500, function () {
                box.style.backgroundColor = 'yellow'
                box.style.padding = 20 + 'px';
            })
        }
        
        function fn(ele, target, callback) {
            // 清除上一次的定时器
            clearInterval(ele.timer)
            // 定时器
            ele.timer = setInterval(function () {
                // 计算步长
                var step = (target - box.offsetLeft) / 10;
                // 取正(向下/向上)
                step = step > 0 ? Math.ceil(step) : Math.floor(step);
                if (box.offsetLeft == target) {
                    clearInterval(ele.timer);
                    // 回调函数
                    if (callback) {
                        callback()
                    }
                    callback && callback()
                }

                box.style.left = box.offsetLeft + step + 'px';
            }, 50)
        }
    </script>
</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值