Home >Web Front-end >JS Tutorial >In-depth analysis of JS OffsetParent attribute_javascript skills
The offsetParent property returns a reference to an object that is closest to the element calling offsetParent (closest in the containing hierarchy) and is a container element that has been CSS positioned. If this container element is not CSS positioned, the value of the offsetParent attribute is a reference to the root element (html element in standards compatibility mode; body element in weird rendering mode). When the container element's style.display is set to "none" (Except for IE and Opera), the offsetParent property returns null.
Syntax:
parentObj = element.offsetParent
Variables:
· parentObj is a reference to an element in which the offset of the current element is calculated.
Testing the OffsetParent property
Conclusion:
When neither an element nor the elements in the DOM structure hierarchy are CSS positioned (absolute or relative) [or an element is CSS positioned Sometimes when elements in the DOM structure hierarchy are not positioned by CSS, the value of the offsetParent attribute of this element is the root element. To be more precise, the reference for various offset calculations (offsetTop, offsetLeft, etc.) of this element is the Body element. (In fact, regardless of standard compatibility mode or weird mode, the root element is the Body element)
Test code 2
Conclusion:
When the parent element of an element is CSS positioned (absolute or relative), the value of the offsetParent attribute of this element is that of its parent element. To be more precise, the reference for various offset calculations (offsetTop, offsetLeft, etc.) of this element is its parent element
Test code 3
测试OffsetParent属性
结论:
当某个元素及其父元素都未进行CSS定位时(absolute或者relative),则这个元素的offsetParent属性的取值为在DOM结构层次中距离其最近,并且已进行了CSS定位的元素。