动画函数-给不同元素记录不同定时器

如果多个元素都使用这个动画函数,每次都要var声明定时器。我们可以给不同的元素使用不同的定时器(自己专门用自己的定时器)。
核心原理:利用Js是一门动态语言,可以很方便的给当前对象添加属性。

示例代码:

<!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>
        div {
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
        }

        span {
            position: absolute;
            top: 150px;
            display: block;
            width: 150px;
            height: 150px;
            background-color: purple;
        }
    </style>
</head>

<body>
    <button>点击111</button>
    <div></div>
    <span>111</span>
</body>
<script>
    // 简单动画函数封装 obj目标对象 target目标位置
    // 给不同的元素指定了不同的定时器
    function animate(obj, target) {
        // 当我们不断的点击按钮,这个元素的速度会越来越快,因为开启了太多的定时器
        // 解决方案就是让我们元素只有一个定时器执行
        // 先清除以前的定时器只保留当前的一个定时器执行
        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 span = document.querySelector('span')
    var btn = document.querySelector('button')
    // 调用函数
    animate(div, 300)
    btn.addEventListener('click', function () {
        animate(span, 200)
    })
</script>

</html>

 

posted @ 2022-04-14 13:30  今天穿秋裤了吗  阅读(48)  评论(0)    收藏  举报