JavaScript-231:简单动画函数封装

效果图

在这里插入图片描述

结构

    <div></div>
   <span></span>

CSS

        div {
    
    
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
        }

        span {
    
    
            position: absolute;
            left: 0;
            top: 100px;
            background-color: red;
            width: 100px;
            height: 100px;
        }

js

        // 简单动画函数封装obj目标对象 target 目标位置
        function animate (obj, target)
        {
    
    
            var timer = setInterval(function ()
            {
    
    
                if (obj.offsetLeft >= target)
                {
    
    
                    // 停止动画 本质是停止定时器
                    clearInterval(timer);
                }
                obj.style.left = obj.offsetLeft + 1 + 'px';
            }, 30)
        }
        var div = document.querySelector('div');
        var span = document.querySelector('span');
        animate(div, 300);
        animate(span, 300);

猜你喜欢

转载自blog.csdn.net/chuan0106/article/details/124608935