美文网首页
js运动之"物体向左右缓冲运动"

js运动之"物体向左右缓冲运动"

作者: RL空RLR空L | 来源:发表于2018-01-17 17:20 被阅读0次
    rl.jpg
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            #div1 {
                width: 100px;
                height: 100px;
                background: red;
                position: absolute;
                left: 0;
                top: 50px;
            }
        </style>
        <script>
            window.onload=function(){
                var oDiv=document.getElementById('div1');
                var oBtn = document.getElementById('btn1');
                oBtn.onclick=function(){
                    startMove();
                };
            };
    
            function startMove(){
                var oDiv=document.getElementById('div1');
                setInterval(function (){
                    var speed=(300-oDiv.offsetLeft)/30;
                    //ceil()向上取整数,物体向右移动时使用。floor()向下取整数,物体向左移动时使用。
                    speed=speed>0?Math.ceil(speed):Math.floor(speed);
                    oDiv.style.left=oDiv.offsetLeft+speed+'px';
                }, 30);
            }
        </script>
    </head>
    <body>
    <input id="btn1" type="button" value="开始运动">
    <div id="div1"></div>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:js运动之"物体向左右缓冲运动"

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