---
title: "读jQuery之十八（元素位置）"
author: "zhouyrt"
date: "2012-04-24T07:09:25Z"
tags: []
categories: ["Web前端"]
slug: "jquery"
draft: false
lastmod: "2012-04-24T07:09:25Z"
id: 1490283
url: "https://snandy.iteye.com/blog/1490283"
---

*本篇所读源码版本为1.7.2*

 

jQuery中提供了获取设置HTML元素位置的接口方法。如下

 

***.offset()***

***.position()***

***.offsetParent()***

***.scrollTop()***

***.scrollLeft()***

 

所有位置相关的代码在项目的offset.js中，总共250行代码。里面还有些未公开的方法，如

 

***getOffset()***

***getWindow()***

***jQuery.offset.bodyOffset()***

***jQuery.offset.setOffset()***

 

它们之间的关系如下

 

![](http://dl.iteye.com/upload/attachment/0066/8485/d3c691a1-6ee9-3986-8bc5-4a5751157f13.png)

 

 

从图中可以看到两个重要的函数.offset()和.position()都依赖于私有的getOffset()。

.position()还依赖于.offsetParent()。offsetParent通过while循环获取最近的定位父元素（position为非static值）。

 

getOffset()函数根据浏览器是否支持getBoundingClientRect得来。如果支持则使用getBoundingClientRect，否则使用while循环不断计算得出位置值。

 

getBoundingClientRect最早是IE中实现的，后主流浏览器都实现了它。因此后面的else判断基本上用不上，jQuery可考虑去掉该段代码。

 

需要注意下.offset()和.position()的区别

.offset()   相对于document（视口）计算的

.position() 相对于其最近的 定位父元素

 

 

此外，.offset()传入一个对象或函数时可以设置元素的位置（setter），而.position()则仅是获取位置（getter）。

 

.offset()作为getter时，获取dispaly:none的元素top，left都将是零。

.offset()作为setter时，如果没有元素的position（此时值为static），那么.offset()方法会将其设置为“relative”以相对于视口进行重新定位。如下

 

```
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
	elem.style.position = "relative";
}
```

 

相关：

[http://www.w3.org/TR/cssom-view/#the-getclientrects](http://www.w3.org/TR/cssom-view/#the-getclientrects)

[https://developer.mozilla.org/en/DOM/element.getBoundingClientRect](https://developer.mozilla.org/en/DOM/element.getBoundingClientRect)

[http://msdn.microsoft.com/en-us/library/ms536433%28VS.85%29.aspx](http://msdn.microsoft.com/en-us/library/ms536433%28VS.85%29.aspx)