使用javascript确定从div顶部到窗口顶部的距离 [英] Determine distance from the top of a div to top of window with javascript
问题描述
如何确定div最顶部到当前屏幕顶部之间的距离?我只想要像素距离到当前屏幕的顶部,而不是文档的顶部。我尝试了一些像 .offset()
和 .offsetHeight
这样的东西,但我无法包装我的围绕它的大脑。谢谢!
How do I determine the distance between the very top of a div to the top of the current screen? I just want the pixel distance to the top of the current screen, not the top of the document. I've tried a few things like .offset()
and .offsetHeight
, but I just can't wrap my brain around it. Thanks!
推荐答案
您可以使用 .offset()
来获取与文档
元素相比的偏移量,然后使用窗口的
元素,用于查找用户滚动页面的距离: scrollTop
属性
You can use .offset()
to get the offset compared to the document
element and then use the scrollTop
property of the window
element to find how far down the page the user has scrolled:
var scrollTop = $(window).scrollTop(),
elementOffset = $('#my-element').offset().top,
distance = (elementOffset - scrollTop);
距离
变量现在保持距离#my-element
元素的顶部和顶部折叠。
The distance
variable now holds the distance from the top of the #my-element
element and the top-fold.
这是一个演示: http://jsfiddle.net/Rxs2m/
注意负值意味着元素高于顶部。
Note that negative values mean that the element is above the top-fold.
这篇关于使用javascript确定从div顶部到窗口顶部的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!