动画原理:给不同对象添加不同定时器

it2023-09-27  80

<!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>

        div,

        p {

            position: absolute;

            left: 0;

            width: 100px;

            height: 100px;

            background-color: pink;

        }

        

        p {

            top: 400px;

            background-color: red;

        }

    </style>

</head>

 

<body>

    <button>点击</button>

    <div></div>

    <p>love u</p>

    <script>

        //动画函数封装,obj目标对象,target目标位置

        function animate(obj, target) {

            //给不同的元素添加不同的定时器

 

            //当我们不断点击按钮,p速度会越来越快,开启许多个定时器

            //解决方案是:让元素只有一个定时器

            //先清除以前的定时器只保留一个定时器

            clearInterval(obj.timer);

            obj.timer = setInterval(function() {

                if (obj.offsetLeft >= target) {

                    // 停止动画 本质是停止定时器

                    clearInterval(obj.timer);

                }

                obj.style.left = obj.offsetLeft + 1 + 'px';

            }, 30);

        }

        var div = document.querySelector('div');

        var p = document.querySelector('p');

        var btn = document.querySelector('button');

        //animate(p, 200);

        animate(div, 300);

 

        btn.addEventListener('click', function() {

            animate(p, 200);

        })

    </script>

</body>

 

</html>

最新回复(0)