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, the DIV position must be calculated so that the DIV is fully displayed.
I plan to use the offset () method to implement this function, but first I need to figure out its function.
Lab:
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 scroll bar appears in the window. Drag the scroll bar and the offset (). Top of the submit button remains unchanged because the distance between the button and the edge on the document remains unchanged.
Figure 2: The DIV in the document has a scroll bar. The offset (). Top of the submit button changes with the DIV scroll bar because the distance between the button and the edge on the document has changed.
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.
Application:
1. 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, scrolltop is available only when the element has a scroll bar and a certain distance. scrolltop = 0 is an element without a scroll bar.
The button submitted above has no scroll bar, and its scrolltop is always equal to 0.
In the past, I had a wrong idea: the elements in the document have the same scroll value as the document. This is wrong. The child element is irrelevant to the container's scroll value.
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 does not have a scroll bar), the controls offsettop and height are calculated.
2. The floating Div remains in the original position when the scroll bar is rolling.
As shown in figure 1,
VaRFirsttop = $ ("floating Div"). Offset (). Top;VaRTop = firsttop +$ (Document). scrolltop (); $ (floating Div). offset ({top: Top });
As shown in figure 2,
VaRTop = $ (floating Div). Offset (). Top; $ ("Floating Div"). offset ({top: Top });
Source Code : offsettraining.rar