Jquery has two methods for obtaining the element position: offset () and position (). What are the similarities and differences between the two methods? What should I pay attention to when using it? When is offset () used and position () used?
Let's take a look at the definitions of these two methods.
Offset ():
Obtains the relative offset of the matching element in the current view.
The returned object contains two integer attributes: top and left. This method is only valid for visible elements.
Position ():
Obtains the offset of a matched element from its parent element.
The returned object contains two integer attributes: top and left. For precise calculation results, use the pixel unit in the padding, border, and fill attributes. This method is only valid for visible elements.
When the position () method is used, the element is actually treated as absolute positioning. The obtained result is that the element is equivalent to the offset of the nearest parent element with absolute or relative positioning.
When position () is used, if all its parent elements are in the default position (static) mode, the processing method is the same as offset (), which is the relative offset of the current window.
The offset () method is used to obtain the offset of the element relative to the current view regardless of how the element is located or how its parent element is located.
With these features, how can we reasonably use position () and offset?
In my personal experience, I usually obtain the position of an element (A) to make another element (B) appear near Element. There are two common cases:
1. Element B to be displayed is stored at the top or bottom of the DOM (that is, its parent element is the body). It is best to use offset () at this time.
2. If the Element B to be displayed is stored under the same parent element of Element A (that is, the sibling node where B is A), it is most appropriate to use position.
To sum up, the position () or offset () should be used depending on the position of the control element B DOM.
Original article: http://www.jb51.net/article/18340.htm