Javascript 如何使用jQuery以px为单位找到与顶部的垂直距离
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7778580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to find the vertical distance from top in px of an element using jQuery
提问by ptamzz
How do I find the vertical distance from the top of the page to where the element exist in the DOM using javascript/jQuery?
如何使用 javascript/jQuery 找到从页面顶部到元素在 DOM 中存在的位置的垂直距离?
I've something like
我有类似的东西
<ul>
<li>one</li>
<li>one</li>
<li>one</li>
<li>one</li>
<li class="test">one</li>
....
....
....
<li>one</li>
</ul>
For example here, I want to find the vertical distance from top of the page to the li#test
element.
例如在这里,我想找到从页面顶部到li#test
元素的垂直距离。
I tried .scrollTop()
but it always comes as 0!
我试过了,.scrollTop()
但它总是为 0!
回答by Rob W
回答by thexfactor
Rob W's answer is correct - that will give you the offset from the top of the full page.
Rob W 的答案是正确的 - 这会给你从整页顶部的偏移量。
If you want to get the offset from the top of the viewable screen, you should do this:
如果你想从可视屏幕的顶部获得偏移量,你应该这样做:
var viewableOffset = $("#li.test").offset().top - $(window).scrollTop();
Hope that helps!
希望有帮助!
回答by Crisan Raluca Teodora
As far as i know .offset()
get the distance between the current scroll position and the top of the document.
据我所知,.offset()
获取当前滚动位置和文档顶部之间的距离。
You need to use this: $("li.test").position().top
你需要使用这个: $("li.test").position().top
回答by rut shah
Use $(element).offset().top and add height of existing fixed elements on the page to it to make it more accurate.
使用 $(element).offset().top 并将页面上现有固定元素的高度添加到它以使其更准确。