JS-匀速运动-运动停止

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>匀速运动停止条件</title>
        <style type="text/css">
        a{display: block;}
        input[type='button']{
            margin-top: 5px;
        }
            .div {
                width: 100px;
                height: 100px;
                background-color: red;
                position: absolute;
                left: 0;
                top: 200px;
                cursor: pointer;
            }
            .div2{
                width: 1px;
                height: 1200px;
                position: absolute;
                left: 300px;
                top: 0;
                background-color: blueviolet;
                /*用这个标杆,发现div1并没有走到300的准确位置,原因是?*/
            }
            .div3{
                width: 1px;
                height: 1200px;
                position: absolute;
                left: 100px;
                top: 0;
                background-color: blueviolet;
                /*用这个标杆,发现div1并没有走到300的准确位置,原因是?*/
            }
        </style>
        <script type="text/javascript">
        window.onload = function(){
            var oBtn = document.getElementById('btn');
            var oBtn2 = document.getElementById('btn2');
            oBtn.onclick = function(){
                start(100);
            }
            oBtn2.onclick = function(){
                start(300);
            }
        }
        var timer = null;
        function start(iTarget){
        var oDiv = document.getElementById('div');
            clearInterval(timer);
            timer = setInterval(function(){
                var speed = 0;
                if(oDiv.offsetLeft<iTarget){
                    speed = 7;
                }else{
                    speed = -7;
                }
                //这种个情况就是速度不能被整除的时候会出现的问题。
                //思路就像到一个地方下车,距离近了就算到了,不一定分要撞到墙上才算到了。
//                ?解决方法:Math.abs():绝对值,一个数,正负号都取正值
                if(Math.abs(iTarget-oDiv.offsetLeft)<=7){
                    clearInterval(timer);
                    //oDiv.style.left = iTarget;
                    //最后忘了加px,所以还是有点距离有点问题。
                    oDiv.style.left = iTarget+'px';
                }else{
                    oDiv.style.left = oDiv.offsetLeft+speed+'px';
                    document.title = oDiv.offsetLeft+','+speed;
                }
                
            },30);
        }
        
        </script>
    </head>

    <body>
        <input type="button" value="到100" id="btn" />
        <input type="button" value="到300" id="btn2" />
        <div class="div" id="div"></div>
        <div class="div2"></div>
        <div class="div3"></div>
    
    </body>

</html>

智能社的开发教程:原址:https://ke.qq.com/webcourse/index.html#course_id=152997&term_id=100174752&taid=766913655494053&vid=v14127nxshc

原文地址:https://www.cnblogs.com/padding1015/p/6403533.html