10-小球移动

小球移动

简述:小球向一个方向定向移动

html部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./js/animate.js"></script>
    <title>Document</title>
</head>
<body>
    <div class="box1" id="box1"></div>
    <div class="box2" id="box2"></div>
</body>
</html>

css部分

   *{margin: 0; padding: 0;}
        .box1{
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            border-radius: 50%;
            top: 0px;
            left: 500px;
        }
        .box2{
            width: 100px;
            height: 100px;
            background-color: skyblue;
            position: absolute;
            border-radius: 50%;
            top: 150px;
            left: 0px;
        }

js部分

<script>
        let box1 = document.getElementById("box1"),
            box2 = document.getElementById("box2");
            console.log(box1);

            animateMoudle.init(box1,0);
            animateMoudle.init(box2,500);

    </script>

animate.js

let animateMoudle = (function () {
    /*
    *  功能:让一个盒子水平运动起来
    *  参数1:盒子   参数2:目标位置
    * */
    function animate(obj, target) {
        clearInterval(obj.timer); // clearInterval(und) 也不会报错
        obj.timer = setInterval(function () {
            let step = 9; // 步长
            let current = obj.offsetLeft; // 得到盒子相对于参考点的偏移量
            step = target >= current ? step : -step;  // 此时step要么是正10  要么是-10
            if (Math.abs(target - current) >= Math.abs(step)) {
                // 距离目标的距离 至少还大于一个步长
                current += step;
                obj.style.left = current + "px";
            } else {
                // 距离目标的距离 已经小于了一个步长
                obj.style.left = target + "px";
                clearInterval(obj.timer);
            }
        }, 17)
    }

    return {
        init:animate
    }
})();


运行效果

小球运动前
在这里插入图片描述小球运动后
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值