简单的碰撞运动
需要的js
//碰撞运动 //对运动的方向以及临界值的处理 function bumpMove(obj) { clearInterval(obj.timer); var speedX = 10; var speedY = 10; timer = setInterval(function() { var L = obj.offsetLeft + speedX; var T = obj.offsetTop + speedY; if(T > document.documentElement.clientHeight - obj.offsetHeight) { T = document.documentElement.clientHeight - obj.offsetHeight; speedY *= -1; } else if(T < 0) { T = 0; speedY *= -1; } if(L > document.documentElement.clientWidth - obj.offsetWidth) { L = document.documentElement.clientWidth - obj.offsetWidth; speedX *= -1; } else if(L < 0) { L = 0; speedX *= -1; } obj.style.left = L + 'px'; obj.style.top = T + 'px'; }, 30); }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" type="text/css" href="../css/public.css"/> <style type="text/css"> #div1{width: 100px;height: 100px;background: red;position: absolute;} </style> <script type="text/javascript" src="../js/rainbow.js"></script> <script type="text/javascript"> window.onload=function(){ var oDiv=document.getElementById("div1"); bumpMove(oDiv); } </script> </head> <body> <div id="div1"></div> </body> </html>