如何使用jQuery找到元素的绝对位置?

本文翻译自: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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值