JS 获取DIV中 鼠标相对位置

转载文章

 

稍作修改 坐标无误差

 

 

<HEAD>  
<TITLE> JS获取DIV相对坐标</TITLE>  
<script type="text/javascript">
	function getX(obj){
		var parObj=obj;  
		var left=obj.offsetLeft;  
	 	while(parObj=parObj.offsetParent){  
	  		left+=parObj.offsetLeft;  
		}  
 		return left;  
	}  
  
	function getY(obj){  
		var parObj=obj;  
		var top=obj.offsetTop;  
		while(parObj = parObj.offsetParent){  
	 		top+=parObj.offsetTop;  
	 	}  
	 return top;  
	}  
  
	function DisplayCoord(event){  
		var top,left,oDiv;  
		oDiv=document.getElementById("demo");  
		top=getY(oDiv);  
		left=getX(oDiv);  
		document.getElementById("mp_x").innerHTML = (event.clientX-left+document.body.scrollLeft)  +"px";  
		document.getElementById("mp_y").innerHTML = (event.clientY-top+document.body.scrollTop) +"px";  	  
	} 
</script>
</HEAD>  
  
<BODY style="margin:40px;" mce_style="margin:40px;">  
<div style="background-color:#000000;color:white;width:300px;height:300px;position:absolute;top:80px;left:90px;margin:0px; border:0px;" id="demo" onmousemove="DisplayCoord(event)">  
我是DIV,经测试,没有误差  
</div>  
当前鼠标坐标为:  
X:<span id="mp_x"></span>  
Y:<span id="mp_y"></span>  
</body>  
</BODY>  
</HTML> 

  转载地址 :http://blog.csdn.net/zm12037/article/details/4869670

 

你可能感兴趣的:(JavaScript,html)