jQuery提供的獲取元素位置的接口方法
HTML元素的位置相關(guān)的css屬性有top、left、bottom、right。要靈活使用這些屬性,需要了解css的定位模型position:正常文檔流,相對(duì)定位,絕對(duì)定位。
了解了這些css知識(shí)才更清楚jQuery的position及offset的區(qū)別。
jQuery中提供了獲取設(shè)置HTML元素位置的接口方法。如下
.offset()
.position()
.offsetParent()
.scrollTop()
.scrollLeft()
所有位置相關(guān)的代碼在項(xiàng)目的offset.js中,總共250行代碼。里面還有些未公開的方法,如
getOffset()
getWindow()
jQuery.offset.bodyOffset()
jQuery.offset.setOffset()
它們之間的關(guān)系如下
從圖中可以看到兩個(gè)重要的函數(shù).offset()和.position()都依賴于私有的getOffset()。
.position()還依賴于.offsetParent()。offsetParent通過while循環(huán)獲取最近的定位父元素(position為非static值)。
getOffset()函數(shù)根據(jù)瀏覽器是否支持getBoundingClientRect得來。如果支持則使用getBoundingClientRect,否則使用while循環(huán)不斷計(jì)算得出位置值。
getBoundingClientRect最早是IE中實(shí)現(xiàn)的,后主流瀏覽器都實(shí)現(xiàn)了它。因此后面的else判斷基本上用不上,jQuery可考慮去掉該段代碼。
需要注意下.offset()和.position()的區(qū)別
.offset() 相對(duì)于document(視口)計(jì)算的
.position() 相對(duì)于其最近的 定位父元素
此外,.offset()傳入一個(gè)對(duì)象或函數(shù)時(shí)可以設(shè)置元素的位置(setter),而.position()則僅是獲取位置(getter)。
.offset()作為getter時(shí),獲取dispaly:none的元素top,left都將是零。
.offset()作為setter時(shí),如果沒有元素的position(此時(shí)值為static),那么.offset()方法會(huì)將其設(shè)置為“relative”以相對(duì)于視口進(jìn)行重新定位。如下
- 1 // set position first, in-case top/left are set even on static elem
- 2 if ( position === "static" ) {
- 3 elem.style.position = "relative";
- 4 }
相關(guān):
http://www.w3.org/TR/cssom-view/#the-getclientrects
https://developer.mozilla.org/en/DOM/element.getBoundingClientRect
http://msdn.microsoft.com/en-us/library/ms536433%28VS.85%29.aspx
原文鏈接:http://www.cnblogs.com/snandy/archive/2012/04/23/2455787.html