<!-- 思路:制作一个div块放一个图片,在移动过程中判断div块是否碰到边界,碰到边界改变方向 -->
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>漂浮</title> 6 <style type="text/css"> 7 *{ 8 margin: 0px; 9 padding: 0px; 10 } 11 #ad{ 12 width: 100px; 13 height: 70px; 14 /*border: 5px solid red;*/ 15 border: 0px; 16 position: absolute; 17 } 18 </style> 19 </head> 20 <body> 21 <div id="ad"> 22 <!-- 设置鼠标进入时执行函数 onmouseover和鼠标离开时执行函数 onmouseout --> 23 <img src="image/01.jpg" width="100px" height="70px" onmouseover="mouseOver()" onmouseout="mouseOut()"> 24 </div> 25 26 <script type="text/javascript"> 27 var ad = document.getElementById("ad"); 28 29 // 获取屏幕的宽度和高度 30 var width = document.documentElement.clientWidth; 31 var height = document.documentElement.clientHeight; 32 var myInterval; //记录执行函数 33 var v_x = 1; //记录向下 1还是向上 -1 34 var v_y = 1; //记录向右 1还是想左 -1 35 function move(){ 36 // 获取某元素x距离左边距离 x.offsetLeft,x自身宽度 x.offsetWidth 37 if(ad.offsetLeft + ad.offsetWidth + 10>= width){ 38 v_x = -1; 39 // clearInterval(myInterval); 40 } 41 // 获取某元素x距离上边边距离 x.offsetTop,x自身高度 x.offsetHeight 42 if(ad.offsetTop + ad.offsetHeight + 10>= height){ 43 v_y = -1; 44 // clearInterval(myInterval); 45 } 46 if(ad.offsetLeft <= 0){ 47 v_x = 1; 48 } 49 if(ad.offsetTop <= 0){ 50 v_y = 1; 51 } 52 53 ad.style.left = ad.offsetLeft + 1*v_x + "px"; 54 ad.style.top = ad.offsetTop + 1*v_y + "px"; 55 56 // alert(ad.offsetRight); 57 } 58 59 myInterval = setInterval(move,10); 60 61 function mouseOver(){ 62 clearInterval(myInterval); 63 } 64 65 function mouseOut(){ 66 myInterval = setInterval(move,1); 67 } 68 </script> 69 </body> 70 </html>