js原生,缓动动画封装

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
             100px;
            height: 100px;
            position: absolute;
            background-color: #ccc;
        }
    </style>
</head>
<body>
    <div class="box"></div>
    <script>
        var box = document.querySelector(".box")
        function animate(obj, target, callback) {
            clearInterval(obj.timer)
            obj.timer = setInterval(() => {
                var step = (target - obj.offsetLeft) / 10
                step = step > 0 ? Math.ceil(step) : Math.floor(step)
                if (obj.offsetLeft === target) {
                    clearInterval(obj.timer)
                    if (callback) {
                        callback()
                    }
                }
                console.log(obj.offsetLeft)
                obj.style.left = obj.offsetLeft + step + 'px'
            }, 40)
        }
        animate(box, 1000)
    </script>
</body>

</html>
原文地址:https://www.cnblogs.com/wjlbk/p/12633367.html