js和jq中常见的各种位置距离之offset()和position()的区别(二)

offset()返回的是相对于当前文档的坐标,position()返回的是相对于其定位的祖辈元素的坐标。

 使用position()方法时事实上是把该元素当绝对定位来处理,获取的是该元素相当于最近的一个拥有绝对或者相对定位的父元素的偏移位置。

 使用position()方法时如果其所有的父元素都为默认定位(static)方式,则其处理方式和offset()一样,是当前窗口的相对偏移,此时如果子元素没有margin,则两者值相同,如果有margin,两者的差值就是子元素的margin值。

 使用offset()方法不管该元素如何定位,也不管其父元素如何定位,都是获取的该元素相对于当前窗口的偏移坐标

附上调试代码:

 1     <style>
 2         *{ margin:0; padding:0;}
 3         #parent{ position:relative; height: 300px; width: 300px; padding: 10px; margin:30px; background-color:#ccc; border: solid 10px #fbc;}
 4         #child{ height: 200px; width: 200px; padding: 10px; margin: 30px; border: 10px solid #fbc;background-color:#afb;}
 5     </style>
 6     <body>
 7         <div id="parent"> 
 8             <div id="child">
 9             </div>
10         </div>
11     </body>
12     <script src="jquery_1.11.3.min.js"></script>
13     <script>
14 
15 
16         console.log( $("#child").offset().left);
17         console.log( $("#child").position().left);
18     </script>

注:此文为原创,如需转载请注明出处。

原文地址:https://www.cnblogs.com/wuqiutong/p/5982693.html