美文网首页
js运动3 匀速运动

js运动3 匀速运动

作者: maomizone | 来源:发表于2017-03-17 17:03 被阅读0次
    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title>缓冲运动</title>
    
        <style>
            *{
                padding: 0;
                margin: 0;
            }
            #btn{
                position: absolute;
                top: 150px;
                left: 20px;
                padding: 5px;
            }
            body div:first-of-type{
                width: 100px;
                height: 100px;
                background: red;
                position: absolute;
                top: 200px;
                left: 700px;
            }
            body div:nth-of-type(2){
                width: 1px;
                height: 500px;
                background: black;
                position: absolute;
                left: 400px;
            }
        </style>
    
        <script>
            window.onload = function(){
                var btn = document.getElementById("btn");
                var target = document.getElementsByTagName("div")[0];
                var endPos = document.getElementsByTagName("div")[1].offsetLeft;
    
                var timer = null;
                btn.onclick = function(){
                    move()
                }
    
                function move(){
                    clearInterval(timer);
                    timer = setInterval(function(){
                        var speed = (endPos - target.offsetLeft)/10;
                        speed = speed>0 ? 7 : -7;
                        target.style.left = target.offsetLeft + speed + "px";
                        document.getElementsByTagName("span")[0].innerHTML = target.offsetLeft+ "," + speed;
                    }, 30);
                }
            }
        </script>
    </head>
    <body>
    
    <button id="btn">移动</button><span></span>
    
    <div>
    
    </div>
    <div>
    
    </div>
    </body>
    </html>
    
    yunsu1.gif

     function move(){
                    clearInterval(timer);
                    timer = setInterval(function(){
                        var speed = (endPos - target.offsetLeft)/10;
                        speed = speed>0 ? 7 : -7;
    
                        if(Math.abs(endPos - target.offsetLeft) <= 7){
                            clearInterval(timer);
                            target.style.left = endPos+"px";
                        }else{
                            target.style.left = target.offsetLeft + speed + "px";
                        }
    
                        document.getElementsByTagName("span")[0].innerHTML = target.offsetLeft+ "," + speed;
                    }, 30);
                }
    
    yunsu2.gif

    相关文章

      网友评论

          本文标题:js运动3 匀速运动

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