获取鼠标的相对位置

function getMousePosition(event,o)
{
 var mousePosition={x:0,y:0};
 var top,left,obj;
    obj=o;
    var ParentObj=obj;

 left=obj.offsetLeft;
 while(ParentObj=ParentObj.offsetParent){
  left+=ParentObj.offsetLeft;
 }
 mousePosition.x=event.clientX-left+document.body.scrollLeft;
 
 ParentObj=obj;
 top=obj.offsetTop;
 while(ParentObj=ParentObj.offsetParent){
  top+=ParentObj.offsetTop;
 }
 mousePosition.y=event.clientY-top+document.body.scrollTop;
 
 return mousePosition;
}

 

///示例:

 

<HTML>
<HEAD>
<TITLE> New Document </TITLE>
</HEAD>

<BODY style="margin:40px;">
<div style="height:400px;">
ddddddddddddddddddddd
</div>
<div style="height:400px;width:300px;background-color:blue;" onmousemove="tellMSPosition(event,this)">
第一个测试DIV
DIV 定位方式:普通定位
</div>
<div style="background-color:#000000;color:#FFFFFF;width:300px;height:300px;position:absolute;top:280px;left:350px;margin:0px; border:0px;" onmousemove="tellMSPosition(event,this)">
第二个测试DIV<br />
DIV 定位方式:绝对定位<br />
<br />
<br />
当前鼠标坐标为:<br />
mousePosition.X:<span id="mp_x"></span><br />
mousePosition.Y:<span id="mp_y"></span>
</div>

</body>

<script type="text/javascript">

function getMousePosition(event,o)
{
 var mousePosition={x:0,y:0};
 var top,left,obj;
    obj=o;
    var ParentObj=obj;

 left=obj.offsetLeft;
 while(ParentObj=ParentObj.offsetParent){
  left+=ParentObj.offsetLeft;
 }
 mousePosition.x=event.clientX-left+document.body.scrollLeft;
 
 ParentObj=obj;
 top=obj.offsetTop;
 while(ParentObj=ParentObj.offsetParent){
  top+=ParentObj.offsetTop;
 }
 mousePosition.y=event.clientY-top+document.body.scrollTop;
 
 return mousePosition;
}
function tellMSPosition(event,o)
{
 var t=getMousePosition(event,o)
 document.getElementById("mp_x").innerHTML = t.x +"px";
 document.getElementById("mp_y").innerHTML = t.y +"px";

}
</script>
</BODY>
</HTML>

posted @ 2009-01-08 11:34  吾非无心  阅读(1196)  评论(1编辑  收藏  举报