How do I find the absolute position of an element using jQuery?

2022-08-29 23:21:45

Is there a way of finding the absolute position of an element, i.e. relative to the start of the window, using jQuery?


答案 1

.offset() will return the offset position of an element as a simple object, eg:

var position = $(element).offset(); // position = { left: 42, top: 567 }

You can use this return value to position other elements at the same spot:

$(anotherElement).css(position)

答案 2

Note that tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed you can get unexpected results.$(element).offset()

If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your element's value will be greater than the expected value by the amount you have scrolled. position:fixedoffset()

If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's value from the fixed element's value. Example: scrollTop()offset().top$("#el").offset().top - $(document).scrollTop()

If the element's offset parent is the document, you want to read instead.position:fixedparseInt($.css('top'))