js gets a method summary of the element's offsets on the page
- 2020-05-27 04:17:31
- OfStack
When creating an js effect, we often need to get the offset of an element on the page (for example, the tip prompt). The offset can be obtained directly relative to the document offset, or relative to the viewport offset (viewpoint) plus the page scrolling (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 iterating up through offsetParent, you can calculate the offset relative to document, which is the offset relative to the page.
Problems with this approach:
1) for pages with tables and inline frames, the results are not accurate due to the differences in how the elements are implemented by different browsers.
2) level 1 is required to search offsetParent upward every time, which is too inefficient.
2. Get the offset (viewpoint) relative to the viewport plus the amount of page scrolling (scroll)
function getOffsetRect(ele){
var box=ele.getBoundingClientRect();
var body=document.body,
docElem=document.documentElement;
// Get the page's 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 Firefox compatible bug
top:Math.round(top),
left:Math.round(left)
}
}
This method directly obtains the offset relative to the viewport through the getBoundingClientRect() method, plus the amount of scrolling on the page, minus clientTop, clientLeft (IE8 and lower browsers use (2,2) as the starting point, so you subtract the starting point from the value. All other browsers use (0,0) as the starting point).
The getBoundingClientRect() method supports IE,ff3+,safari4+,Orear9,5,Chrome.
3. Compatibility
// Gets the offset of the element relative to the page
function getOffset(ele){
if(ele.getBoundingClientRect){
return getOffsetRect(ele);
}else{
return getOffsetSum(ele);
}
}
Browsers that support the getBoundingClientRect() method use the getOffsetRect() method, and those that don't use the getOffsetSum() method.
The above is the whole content of this article, I hope it can help you to learn javascript.