本文翻译自:How do I find the absolute position of an element using jQuery?
有没有办法使用jQuery找到元素的绝对位置,即相对于窗口的开始?
#1楼
参考:https://stackoom.com/question/2rlb/如何使用jQuery找到元素的绝对位置
#2楼
Note that $(element).offset()
tells you the position of an element relative to the document . 请注意, $(element).offset()
告诉您元素相对于文档的位置 。 This works great in most circumstances, but in the case of position:fixed
you can get unexpected results. 这在大多数情况下效果很好,但在position:fixed
的情况下,您可以获得意想不到的结果。
If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed
element's offset()
value will be greater than the expected value by the amount you have scrolled. 如果您的文档比视口长,并且您已垂直向文档底部滚动,那么您的position:fixed
元素的offset()
值将比您滚动的数量大于预期值。
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 scrollTop()
value from the fixed element's offset().top
value. 如果要查找相对于视口 (窗口)的值,而不是位置:fixed元素上的文档,则可以从固定元素的offset().top
值中减去文档的scrollTop()
值。 Example: $("#el").offset().top - $(document).scrollTop()
示例: $("#el").offset().top - $(document).scrollTop()
If the position:fixed
element's offset parent is the document , you want to read parseInt($.css('top'))
instead. 如果position:fixed
元素的偏移父元素是文档 ,则需要读取parseInt($.css('top'))
。
#3楼
.offset()
will return the offset position of an element as a simple object, eg: .offset()
将元素的偏移位置作为简单对象返回,例如:
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)