首页 > 代码库 > JS运动基础

JS运动基础


<!
DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> #div1{ width: 200px; height: 200px; background: red; position: absolute; top:50px; left: 0px; } </style> <script> function startMove(){ var oDiv=document.getElementById(div1); setInterval(function(){ oDiv.style.left=oDiv.offsetLeft+10+px; },30) } </script> </head> <body> <input id="btn1" type="button" value="开始运动" onclick="startMove()"> <div id="div1" ></div> </input> </body> </html>

技术分享

 

 

设置停顿位置和移动速度

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        #div1{
            width: 200px;
            height: 200px;
            background: red;
            position: absolute;
            top:50px;
            left: 0px;
        }
    </style>
    <script>
        //开启定时器
        var timer=null;
        function startMove(){
            var speed=3;
            var oDiv=document.getElementById(div1);
            timer=setInterval(function(){
                if(oDiv.offsetLeft>=300){//停顿位置
                    clearInterval(timer);
                }
                    oDiv.style.left=oDiv.offsetLeft+speed+px;//speed是物体运动速度快慢
                },30);
        }
    </script>
</head>
<body>
<input id="btn1" type="button" value="开始运动" onclick="startMove()">
    <div id="div1" ></div>
</input>
</body>
</html>

技术分享

 

JS运动基础