JavaScript运动之均速运动

1.在开始运动时,关闭已有定时器

 2.把运动和停止隔开(if/else)

demo:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #content {
            width: 50px;
            height: 50px;
            background: red;
            position: absolute;
            left: 0px;
            top:50px;
            cursor: pointer;
        }
        #contentTwo{
            width: 1px;
            height: 350px;
            background: black;
            position: absolute;
            left: 100px;
            top:0px;
        }
        #contentThir{
            width: 1px;
            height: 350px;
            background: black;
            position: absolute;
            left: 300px;
            top:0px;
        }
    </style>
</head>
<body>
    <input type="button" value="100" id="btn">
    <input type="button" value="300" id="btn2">
    <div id="content"></div>
    <div id="contentTwo"></div>
    <div id="contentThir"></div>
    <script>
        var cont=document.getElementById('content');
        var btn=document.getElementById('btn');
        var btn1=document.getElementById('btn2');
        var timer;
        btn.onclick=function(){
            startMove(100); 
        }
        btn1.onclick=function(){
            startMove(300);
        }
        function startMove(target){
            clearInterval(timer)
            timer=setInterval(function(){
                var speed=0;
                if(cont.offsetLeft > target){
                    speed=-5;
                }else{
                  speed=5;
                }
               if(Math.abs(target-cont.offsetLeft) <= 5){
                    clearInterval(timer);
                    cont.style.left=target + 'px';
               }else{
                cont.style.left=cont.offsetLeft + speed +'px';
               }
                
            },30)
        }

    </script>
</body>

</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值