JavaScript中的坐标系问题

在JavaScript中有三种不同的坐标系:屏幕坐标,窗口(viewport)坐标和文档(document)坐标。其中要注意的是文档坐标和窗口坐标的关系。窗口坐标的原点是其视口的作上角,由于窗口具有滚动条,文档的坐标原点可能会滚动到窗口以外,这时要注意两者的关系。在代码的书写过程中要注意的是JavaScript的AIP返回的值是基于什么坐标系的。在利用javaScript来操纵css style的时候中的时候absolute的坐标是相对于document坐标系的。
 
以下是一些常见的坐标问题
1.document中elemenet的位置和大小
   每个element都有四个属性:offsetleft,offsetTop,OffsetHeight,offsetWidth,这四个属性分别代表的是element的左上角和高宽。
最初是由IE4引入的,后来也得到了其他浏览器的支持。但是这些属性值相对于该element的offsetParent的坐标.在<html>文件中中<body>的offsetParent为null,因此要得到一个elment的坐标的正确方法是
getElementX(e)
{
 var x=0;
 while(e)
  {
   x+=e.offsetLeft;
   e=e.offsetParent;
  }
 return x;
}
这个方法的返回值是相对于document的坐标的,它不会受到窗口是否滚动的影响。
但是这种方法还有一个小问题,那就是一个element通过设置它的css属性overflow可以拥有自身的滚动条,这时以这种方法得到的只是不正确的。这时正确的方法如下
function getY(element)
{
// Iterate the offsetParents
// Add up offsetTop values
    var y = 0;
    for(var e = element; e; e = e.offsetParent)
        y += e.offsetTop;                      
    // Now loop up through the ancestors of the element, looking for
    // any that have scrollTop set. Subtract these scrolling values from
    // the total offset. However, we must be sure to stop the loop before
    // we reach document.body, or we'll take document scrolling into account
    // and end up converting our offset to window coordinates.
    for(e = element.parentNode; e && e != document.body; e = e.parentNode)
     // subtract scrollbar values
  if (e.scrollTop) y -= e.scrollTop; 
    // This is the Y coordinate with document-internal scrolling accounted for.
    return y;
}
2.鼠标事件中的坐标问题
 在DOM2的时间模型中的MouseEvent对象和IE的时间模型中的Event对象都有一对属性clinetX和clientY属性,它们表明的是鼠标事件发生时鼠标在viewport坐标中的位置,他们都没有考虑doucument的滚动。如果要得到docuemnt做坐标系下的位置,则应加上windows.pageOffsetX和windows.pageOffsetY的值.

 

本文转自http://moneylcj.spaces.live.com/blog/cns!D43E59CB7117D485!125.entry

posted on 2008-09-08 08:39  YISONG  阅读(1692)  评论(0)    收藏  举报

导航