We sometimes need to implement this function: click a button and a div is displayed below the button. When the button is in the corner, adjust the div position. Otherwise, the div is not completely displayed.
I plan to use the offset () method to implement this function, but first I need to figure out its function.
The top of offset () refers to the distance between the element and the document, rather than the top edge of the current browser form, 1.
Figure 1: when the document height exceeds the window, the browser displays a scroll bar and the offset of the submit button remains unchanged.
Figure 2: The div in the document has a scroll bar. the offset of the submit button changes with the scroll of the div, regardless of the document.
Offset (). left is the same.
Through the above experiment, we can draw the following conclusion: offset () is used to obtain the pixels from the element (html element) to the top and left edges of the document, we only need to know that the document part in the browser is the correct offset (). For more information about document, see JQuery window, document, and body.
How can we ensure that all elements are displayed in the browser window? We can combine offset and scrollTop.
What value does scrollTop obtain? According to my experiment, only elements with a scroll bar and a certain distance can have a scrollTop value. elements without a scroll bar have scrollTop = 0. For example, the scrollTop of a button is always equal to 0. In the past, I had a wrong idea: the document has the same scroll value as the child element in it. This is wrong. The child element has nothing to do with the scroll value of the container.
As shown in figure 1 (document has a scroll bar), you need to calculate the control's offsetTop, height, and scrollTop of the document;
As shown in figure 2 (document has no scroll bar), calculate the control's offsetTop and height.
Source code: jquery_offset.rar