Home  >  Article  >  Web Front-end  >  jquery offset function application example_jquery

jquery offset function application example_jquery

WBOY
WBOYOriginal
2016-05-16 17:48:141303browse

Sometimes we need to implement such a function: click a button and then display a div below the button. When the button is located in the corner, the position setting of the div needs to be adjusted, otherwise, the div will not be fully displayed.

I plan to use the offset() method to implement this function, but I need to figure out its function first.

The top of offset() refers to the distance between the element and the top of the document, not the top edge of the browser's current form, as shown in Figure 1.

Figure 1: The height of the document exceeds the window, a scroll bar appears in the browser, the scroll bar is scrolled, 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 scrolling of the div and has nothing to do with the document

offset().left is the same.

Through the above experiments, we can draw the following conclusions: offset() obtains the pixels that refer to the distance between the element (html element) and the upper edge and left edge of the document. As long as we know which part of the document is in the browser, we can use offset( correctly ). About document, you can read JQuery window, document, body

So how do we ensure that the element is completely displayed in the browser window? We can achieve this by combining offset and scrollTop.

What value does scrollTop get? According to my experiments, only elements with scroll bars and scrolled a certain distance will have a scrollTop value. Elements without scroll bars have scrollTop=0. For example, the scrollTop of a button is always equal to 0. I used to have a wrong understanding: the document and the child elements inside it have the same scroll value. This is wrong. The child elements have nothing to do with the scroll value of the container.

According to Figure 1 (the document has scroll bars), it is necessary to calculate the offsetTop and height of the control, and the scrollTop of the document;

According to Figure 2 (document has no scroll bar), calculate the offsetTop and height of the control

Source code:jquery_offset.rar

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn