When using JS to make an effect, we often want to get an element's offset on the page (such as the Tip tip box feature). The get offset can be obtained directly relative to the document offset, or relative to the viewport offset (viewpoint) plus the page scroll amount (scroll).
1. Get offset relative to document
function Getoffsetsum (ele) { var top= 0,left=0; while (ele) { top+=ele.offsettop; Left+=ele.offsetleft; ele=ele.offsetparent; } return { top:top, left:left }}
By iterating up the offsetparent, you can calculate the offset relative to the document, that is, the offset from the page.
Problems with this method:
1) for pages that use tables and inline frame layouts, the results are inaccurate due to differences in how elements are implemented in different browsers.
2) Each time a first-level search for offsetparent is required, the efficiency is too low.
2. Get the relative offset to the viewport (viewpoint) plus the scrolling amount of the page (scroll)
function Getoffsetrect (ele) { var box=ele.getboundingclientrect (); var body=document.body, docelem=document.documentelement; Get page scrolltop,scrollleft (compatibility notation) var scrolltop=window.pageyoffset| | docelem.scrolltop| | Body.scrolltop, scrollleft=window.pagexoffset| | docelem.scrollleft| | Body.scrollleft; var clienttop=docelem.clienttop| | Body.clienttop, clientleft=docelem.clientleft| | Body.clientleft; var top=box.top+scrolltop-clienttop, Left=box.left+scrollleft-clientleft; return { //math.round compatible with Firefox bug Top:Math.round (top), Left:Math.round (left) } }
This method obtains the offset from the viewport directly through the Getboundingclientrect () method, plus the scroll amount of the page, minus Clienttop,clientleft (IE8 and lower versions of the browser (2,2) as the starting coordinates. So to subtract the value from the start coordinate, the other browsers are already (0,0) as the start coordinates.
The Getboundingclientrect () method supports Ie,ff3+,safari4+,orear9,5,chrome.
3. Compatibility wording
Gets the offset of the element relative to the page function GetOffset (ele) { if (ele.getboundingclientrect) { return getoffsetrect (ele); } else{ return Getoffsetsum (ele); }}
For browsers that support the Getboundingclientrect () method, use the Getoffsetrect () method, and the Getoffsetsum () method is not supported.
Reference:
Http://javascript.info/tutorial/coordinates#element-coordinates-by-offsetparent
JS the best way to get the offset of an element on a page