非原创 来源于其它作者
第一种
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <style type="text/css"> 9 #demo { 10 width: 100px; 11 height: 100px; 12 position:absolute; 13 border-radius:50px; 14 } 15 </style> 16 17 <script type="text/javascript"> 18 window.onload = function(){ 19 var demo = document.getElementById('demo'); 20 var sx = sy = 10; 21 var x = y = 0; 22 23 function move(){ 24 if(document.documentElement.clientWidth - demo.offsetWidth-10 < x || x < 0){ 25 sx = -sx; 26 } 27 28 if(document.documentElement.clientHeight - demo.offsetHeight-10 < y || y < 0){ 29 sy = -sy; 30 } 31 32 x = demo.offsetLeft + sx; 33 y = demo.offsetTop + sy; 34 35 demo.style.left = x + 'px'; 36 demo.style.top = y + 'px'; 37 } 38 39 var timer = setInterval(move, 100); 40 41 demo.onmouseover = function(){ 42 clearInterval(timer); 43 } 44 45 demo.onmouseout = function(){ 46 timer = setInterval(move, 100); 47 } 48 } 49 </script> 50 51 <img src="http://d.hiphotos.baidu.com/image/w%3D2048/sign=48fd3c26f01fbe091c5ec4145f580d33/64380cd7912397dd92729b545b82b2b7d0a28752.jpg" id="demo" /> 52 53 </body> 54 </html>
第二种
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <script> 7 var directX=1;//x轴的方向 8 var directY=1;//y轴的方向 9 var moveX=0;//图片的坐标 10 var moveY=0; 11 var speed=2;//移动的速度 12 function move(){ 13 moveX+=directX*speed; 14 moveY+=directY*speed; 15 var nr=document.getElementById("moveDiv"); 16 nr.style.top=moveY+"px";//改变div 的top 17 nr.style.left=moveX+"px";//改变div的left 18 if (moveX+nr.offsetWidth>=document.body.clientWidth||moveX<=0){ 19 directX=-directX;//当碰触到边界的时候 改变方向 20 } 21 if (moveY+nr.offsetHeight>=document.documentElement.clientHeight||moveY<=0){ 22 directY=-directY; 23 } 24 } 25 setInterval(move,20); 26 27 </script> 28 </head> 29 <body> 30 <div id="moveDiv" style=" position: absolute;"> 31 <img src="http://img.mp.sohu.com/upload/20170813/60c7210c02ed4404ba29bfc149dffec3.png"> 32 </div> 33 </body> 34 </html>