A Brief Talk on offsetleft offsetTop and offsetParent
- 2021-10-11 17:35:50
- OfStack
ele. offsetParent returns the nearest and located parent of ele element (relative, absolute). If there is no parent element or none of the parent elements is located, the return value is body element
The value problem of ele. offsetLeft and ele. offsetTop can be divided into many situations:
If ele is a direct child of body, the return value is the distance from ele to the left or top of bodyIf ele is not a direct child of body, when the parent element is positioned (relative, absolute), the return value of each browser is ele to the left of the parent element or
The distance at the top (the only difference of 1 is that chrome does not include the border, while IE and firefox are all included)
If ele is not a direct child element of body and the parent element is not located, each browser returns the direct distance between ele and body
It can be seen from the above that the value returned by offsetLeft and offsetTop is the distance from ele to offsetParent. What element this offsetParent is depends on whether the parent element of ele is positioned (relative, absolute)
Application:
In order to obtain the distance between the elements and the left side of the web page, we should consider the positioning of offsetParent. We can't simply get it with ele. offsetLeft/Top. We must get the correct value through circular accumulation (chrome's result is different from IE and Firefox, and the difference is 1px, because chrome doesn't calculate the border). The following is the code
(Tips: this. left, this. top in the code can be replaced by arguments. callee, but it is not recommended according to ECMAScript 5 specification, and it has been disabled under strict model, because arguments is a relatively large object and consumes a lot of resources.)
var getOffset = {
left:function(obj){
return obj.offsetLeft + (obj.offsetParent ? this.left(obj.offsetParent) : 0);
},
top:function(){
return obj.offsetTop + (obj.offsetParent ? this.top(obj.offsetParent) : 0);
}
}