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

2018-01-17  本文已影响0人  RL空RLR空L
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>
上一篇下一篇

猜你喜欢

热点阅读