Click a button and a div is displayed below the button. When the button is in the corner, adjust the position of the div. Otherwise, the div is not completely displayed. I plan to use the offset () method to implement this function. Sometimes we need to implement this function: click a button and a p is displayed below the button. When the button is in the corner, the position of p needs to be adjusted. Otherwise, p 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.
: When the document height exceeds the window, the browser displays a scroll bar. the offset of the submit button remains unchanged.
: P in document has a scroll bar, And the offset of the submit button changes with the scrolling of p, not related to 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.
Press (document has a scroll bar) to calculate the control's offsetTop, height, and scrollTop of the document;
Press (document has no scroll bar) to calculate the control's offsetTop and height
Source code: jquery_offset.rar