offsetParent offsetTop offsetLeft

在进行js编程的时候元素的offsetTop和offsetLeft,当用到他们的时候,有时候会牵扯到元素的offsetParent属性。先 来看看W3C的解释:
     offsetParent

返回对最近的动态定位的包含元素的引用,所有的偏移量都根据该元素来决定。如果元素 的 style.display 设置为 none,则该属性返回 null。这是非标准的但却得到很好支持的属性。

类型:Node。状态:只读。

    
     offsetLeft

返回当前元素的左边界到它的包含元素的左边界的偏移量,以像素为单位。

类型:int。状态:只读。

     offsetTop

返回当 前元素的上边界到它的包含元素的上边界的偏移量,以像素为单位。

类型:int。状态:只读。

   如下代码: 

  

1   <style type="text/css" media="all">
2   .border
3    {
4      font-size:12px;
5      border:#FF0000  solid 1px;
6    }
 1 <div id="outer" style="height:300px; 300px; position:absolute;">
 2     <div class="border" style="height:200px; 200px;" id="out">
 3         <div class="border"id="iner">inner元素</div>
 4     </div>
 5 </div>
 6 <script language="javascript" type="text/javascript">
 7 var outDiv=document.getElementById("out");
 8 var inDiv=document.getElementById("iner");
 9 var oP=inDiv.offsetParent;
10 alert(oP.id);
11 alert(iner.offsetTop);
12 alert(iner.offsetLeft);
13 alert(iner.scrollTop);
14 alert(iner.scrollLeft);
15 </script>
  出现的结果是:out,即id为iner的DIV的offsetParent为out(DIV), alert弹出的结果随浏览器的不同而不同。注意在这里要给iner的父元素(out)加postion属性,如果没有设置,获取的将是Body节点,当 然如果获取的是body节点,那么iner.offsetTop和iner.offsetLeft的值就会参照body标签的距离,结果为 95(94)、9(8)、0 、0 。如果为out,结果为1(0)、1(0)、0、0。
可以看到,上面的解释不够具 体,可总结为:
 offsetLeft:获取元素(iner)相对于版面(body)或由该元素的 offsetParent 属性指定的元素(out)的左侧位置到该元素(iner)左边框的位置。
 offsetTop:
获 取元素(iner)相对于版面(body)或由该元素的offsetParent 属性指定的元素(out)的顶侧位置到该元素(iner)顶部的位置。
原文地址:https://www.cnblogs.com/Logen/p/1691022.html