运动模块1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>移动案例</title>
    <style>
        .box{
            width: 100px;
            height: 100px;
            background-color: green;
            position: absolute;
            top: 100px;

        }
    </style>
</head>
<body>
<input type="button" value="移动到400px" id="btn1">
<input type="button" value="移动到800px" id="btn2">
<br>
<div class="box" id="dv"></div>
<script>
    function $(id) {
        return document.getElementById(id)

    }
    //运动框架
    function animate(ele,target,step) {
        let s = step //把当前的步数进行记录
        //先清理定时器
        clearInterval(ele.timer)
          ele.timer = setInterval(function () { //ele是一个对象,把定时器的变量变为一个对象的属性
            //获取当前的div的位置
            var current = ele.offsetLeft;
            //div移动的步数
            //判断是从左或从右走
            step = current<target?s:-s;//当前的距离小于目标值时,需要为正的步数,否则为负数
            //每次移动后的距离
            current+= step;
            //判断当前移动后的位置是否到达目标位置
            if(Math.abs(target-current)>Math.abs(step)){  //当为负数时,有绝对值比较数字
                ele.style.left = current+'px';//当大于步数时,说明还有距离
            }else{
                clearInterval(ele.timer)
                ele.style.left = target+'px';  //当小于步数时,说明当时已经接近目标,就直接让他到目标位置
            }
        },20)

    }

    $('btn1').onclick = function () {
        animate($('dv'),400,10)
    };
    $('btn2').onclick = function () {
        animate($('dv'),800,10)
    }

    function Move(left,step,ele) {
        var current = ele.offsetLeft; //获取当前的位置
        current +=step;
        if(current<=left){
            ele.style.left = current+'px';
        }else{
            return;
        }
    }
    //匀速前进,最终移到400px,
    // var timer = null; //只产生一个定时器
    // $('btn1').onclick = function () {
    //     setInterval(function() {
    //         Move(400,10,$('dv'))
    //     }, 20)
    //
    //     //setInterval(Move(400,10),20)
    // }
    // $('btn2').onclick = function () {
    //     setInterval(function () {
    //         Move(800,10,$('dv'))
    //     },20)
    // }
</script>
</body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值