因爲offsetTop 和 offsetLeft 都是相對於 offsetParent 內邊距邊界的,故offsetParent的意義十分重大。offsetParent的機制與css中包含塊的概念十分相似但並不徹底一致,其不一致有時候是因爲瀏覽器的不一樣而致使的,例如:當元素爲固定定位時(fixed),chrome瀏覽器的 offsetParent 值爲 Null,而火狐的則爲 body 元素。總結規律以下:css
自己定位爲fixed | 自己定位非fiexd | |||
offsetParent | 火狐 | 非火狐 | 父級無定位 | 父級有定位 |
body | null | body | 有定位的父級 |
offsetLeft 是一個只讀屬性,返回當前元素左上角相對於 offsetParent 節點的左邊界偏移的像素值。 html
offsetTop 爲只讀屬性,它返回當前元素相對於其 offsetParent 元素的頂部的距離。node
function getPointAb(node){ //while循環疊加offsetParent的offsetTop和offsetLeft var x =0; var y = 0; while(node){ x+=node.offsetLeft; y+=node.offsetTop; node = node.offsetParent; } return {x:x,y:y}; }
L = document.documentElement.scrollLeft||document.body.scrollLeft;
T = document.documentElement.scrollTop||document.body.scrollTop;
//boder margin會影響這個函數的取值 function getPointRe(node){ //while循環疊加offsetParent的offsetTop和offsetLeft var x =0; var y = 0; while(node){ x+=node.offsetLeft; y+=node.offsetTop; node = node.offsetParent; } var L = document.documentElement.scrollLeft||document.body.scrollLeft; var T = document.documentElement.scrollTop||document.body.scrollTop; return {x:x-L,y:y-T}; }
tips:在ie10及ie10如下,根標籤的clientWidth和offsetWidth,統一被指定爲視口的寬度。chrome