获取HTML元素位置--js学习笔记

对于不同的元素,不同的浏览器,offsetParent含义不同,有时,指的是直接包含的元素,有时指的是HTML元素,有时不存在offsetParent.

如果所研究的元素没有offsetParent,仅计算该元素自身的偏移位置,否则要将元素的偏移值加到元素的offsetParent偏移值,再重复上面步骤,一级一级递归。

function getPosition(theElement){

    var positionX = 0;
    var positionY = 0;  
    
    while(theElement != null){
         positionX += theElement.offsetLeft;
         positionY += theElement.offsetTop;
         theElement = theElement.offsetParent;
  
    }

     return [positionX,positionY];
}

Mac下的IE5还考虑了body页变空白或边框距,精确地度量尺度,应该使body上的页边空白和边框距为0.

 

posted @ 2014-04-17 15:05  nan  阅读(420)  评论(0编辑  收藏  举报