1 /* 2 *JS回弹原理 3 */ 4 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 8 <title>无标题文档</title> 9 <style type="text/css"> 10 *{padding: 0; margin: 0;} 11 #div1{ width: 100px; height: 100px; background: red; position: absolute;} 12 </style> 13 14 <script type="text/javascript"> 15 window.onload = function(){ 16 17 setInterval(function(){startMove("div1");},30); 18 19 var iSpeedX = 7; //在X方向的运动速度 20 var iSpeedY = 17; //在Y方向的运动速度 21 function startMove(id){ 22 var oDiv = document.getElementById(id); 23 var l = oDiv.offsetLeft + iSpeedX; 24 var t = oDiv.offsetTop + iSpeedY; 25 26 if(t > document.documentElement.clientHeight - oDiv.offsetHeight){ //如果当前运动的物体Top位置大于屏幕高度 27 t = document.documentElement.clientHeight - oDiv.offsetHeight; //限制高度 28 iSpeedY *= -1; //把速度变成负的,回弹。 29 } 30 if(t < 0){ 31 t = 0; 32 iSpeedY *= -1; 33 } 34 if(l > document.documentElement.clientWidth - oDiv.offsetWidth){ 35 l = document.documentElement.clientWidth - oDiv.offsetWidth; 36 iSpeedX *= -1; 37 } 38 if(l < 0){ 39 l = 0; 40 iSpeedX *= -1; 41 } 42 43 oDiv.style.left = l + "px"; 44 oDiv.style.top = t + "px"; 45 46 document.title = l + " , " + t + "," + iSpeedX + "," + iSpeedY; 47 48 } 49 } 50 </script> 51 52 </head> 53 54 <body> 55 56 <div id="div1"></div> 57 58 </body> 59 </html>