Javascript can obtain the offset of an element through four attributes: 1, offsetHeight, 2, offsetWidth, 3, offsetLeft, 4, and offsetTop, today, let's talk about the best way to get the offset of page elements. When using js to create an effect, we often need to get the offset of an element on the page (for example, the tip prompt box function ). The offset can be used to directly obtain the offset relative to the document, or the offset relative to the viewpoint and the page scroll.
1. get the 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 iterative offsetParent up, you can calculate the offset relative to the document, that is, the offset relative to the page.
Problems with this method:
1) for pages that are laid out using tables and embedded frameworks, the results are inaccurate due to differences in the implementation of elements in different browsers.
2) you need to search for offsetParent at the first-level and up each time, which is too inefficient.
2. get the offset (viewpoint) of the relative and the viewport plus the page scroll volume (scroll)
Function getOffsetRect (ele) {var box = ele. getBoundingClientRect (); var body = document. body, docElem=document.doc umentElement; // Obtain the scrollTop and scrollLeft of the page (compatibility) 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 browser bug top: Math. round (top), left: Math. round (left )}}
This method uses the getBoundingClientRect () method to obtain the offset relative to the viewport, plus the page scroll volume, minus the clientTop, and the clientLeft (IE8 and earlier browsers use () as the starting coordinate, therefore, we need to subtract the starting point coordinate from the value. Other browsers use (0, 0) as the starting point coordinate ).
The getBoundingClientRect () method supports IE, ff3 +, safari4 +, Orear9, 5, Chrome.
3. compatibility
// Get the offset function getOffset (ele) {if (ele. getBoundingClientRect) {return getOffsetRect (ele);} else {return getOffsetSum (ele );}}
For browsers that support the getBoundingClientRect () method, use the getOffsetRect () method. if not, use the getOffsetSum () method.
The above is all the content of this article, hoping to help you learn javascript.