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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:34:11  来源:igfitidea点击:

how to find the vertical distance from top in px of an element using jQuery

javascriptjquery

提问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#testelement.

例如在这里,我想找到从页面顶部到li#test元素的垂直距离。

I tried .scrollTop()but it always comes as 0!

我试过了,.scrollTop()但它总是为 0!

回答by Rob W

Use .offset()to get the distance between an element and the top of the document:

使用.offset()获取元素和文档的顶部之间的距离:

$("li.test").offset().top

回答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 并将页面上现有固定元素的高度添加到它以使其更准确。