美文网首页
03js匀速运动的优化版本

03js匀速运动的优化版本

作者: An的杂货铺 | 来源:发表于2019-03-12 10:20 被阅读0次
<!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>
        * {
            margin: 0;
            padding: 0;
        }
        .box {
            width: 100px;
            height: 100px;
            background-color: pink;
            position: absolute;
            left: 0;
            top: 100px;
        }
    </style>
</head>
<body>
    <button id="btn">move-></button>
    <button id="btnone"> <-move</button>
    <div class="box"></div> 
    <script>
        var btn = document.getElementById('btn');
        var btnone = document.getElementById('btnone');
        var odiv = document.getElementsByTagName('div')[0];
        var timer = null;//初始化一个定时器
        var num = 0;
        //在之前的基础上继续封装只传一个参数
        btn.onclick = function(){
           move(500);
        }
        btnone.onclick = function(){
           move(0)
        }
        // function move(length){
        //     clearInterval(timer);
        //     var speed = length-odiv.offsetLeft>0?5:-5;
        //     timer = setInterval(function(){
        //         num+=speed;
        //         if(odiv.offsetLeft === length){
        //         clearInterval(timer);
        //     }else{
        //         odiv.style.left = num+'px';
        //     }

        //     },20)
        // }
        //较之于1和2更加简洁,以上是让速度为5或者-5,能够正好到达target,当不能正好累加到target时另作处理,如下
        function move(target){
            clearInterval(timer);
            timer = setInterval(function(){
              var speed = target-odiv.offsetLeft>0?7:-7;
              num+=speed;
              if(Math.abs(target-odiv.offsetLeft)<7){
                 odiv.style.left = target+'px';
                 //当以7px/20ms速度移动时不能正好到达target,此时需要强制拉到终点
                 clearInterval(timer);
              }else{
                 odiv.style.left = num+'px';
              }
            },20)
        }

    </script>    
</body>
</html>

如图


image.png

相关文章

网友评论

      本文标题:03js匀速运动的优化版本

      本文链接:https://www.haomeiwen.com/subject/rucgpqtx.html