js 简单动画

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div {
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>
</head>
<body>
<div></div>
<script>
    var div = document.querySelector('div');
    //获取元素当前位置,并让盒子在当前位置加上1个距离
    div.style.left = div.offsetLeft + 1 + 'px';
    //利用定时器不断重复上述操作
    var timer = setInterval(function () {
        if (div.offsetLeft >= 400) {
            //停止
            clearInterval(timer);
        }
        div.style.left = div.offsetLeft + 1 + 'px';
    }, 3)
</script>
</body>
</html>

封装到函数中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div {
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
        }

        span {
            position: absolute;
            left: 0;
            top: 200px;
            display: block;
            width: 150px;
            height: 150px;
            background-color: purple;
        }
    </style>
</head>
<body>
<div></div>
<span>高瑶</span>
<script>
    function animate(obj, target) {
        var timer = setInterval(function () {
            if (obj.offsetLeft >= target) {
                //停止
                clearInterval(timer);
            }
            obj.style.left = obj.offsetLeft + 5 + 'px';
        }, 30);
    }

    var div = document.querySelector('div');
    var span = document.querySelector('span');
    /*//获取元素当前位置,并让盒子在当前位置加上1个距离
    div.style.left = div.offsetLeft + 1 + 'px';
    //利用定时器不断重复上述操作*/
    animate(div, 300);
    animate(span, 200);
</script>
</body>
</html>

优化函数后

function animate(obj, target) {
        clearInterval(obj.timer);
        obj.timer = setInterval(function () {
            if (obj.offsetLeft >= target) {
                //停止
                clearInterval(obj.timer);
            }
            obj.style.left = obj.offsetLeft + 5 + 'px';
        }, 30);
    }

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值