<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style> .one{ 200px; height:220px; background-color:#CC3; position:absolute; top=0px; left=0px; } </style> <script> //div1.offsetHeight实际元素的高度 数值一直都是220 不带单位px //div1.offsetLeft 当前元素的位置 window.onload = function(){ var div1= document.getElementsByTagName("div")[0]; var span1= document.getElementsByTagName("div")[0]; var sx=5,sy=5,x,y; var time = setInterval(func,20); function func(){ if(document.documentElement.clientWidth-x<div1.offsetWidth || x<0) { sx = -sx; } if(document.documentElement.clientHeight - y<div1.offsetHeight ||y<0){ sy = -sy; } x = div1.offsetLeft + sx; y = div1.offsetTop + sy; div1.style.left = x +"px"; div1.style.top = y +"px"; // alert(div1.offsetHeight); //alert(div1.offsetLeft); } div1.onmouseover=function(){ clearInterval(time); } div1.onmouseout=function(){ time = setInterval(func,20); } span1.onclick=function(){ document.body.removeChild(div1); div1=null; } } </script> </head> <body> <div class="one"> <span>X</span> </div> </body> </html>