How do I find the vertical distance from the top of the page to where the element exist in the DOM using javascript/jQuery?

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.

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

推荐答案

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

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

Jquery相关问答推荐

使用 JQuery 在 span 标签中用逗号分隔页面上的文本

用 jQuery/JavaScript 检测数字或字母?

jQueryUI 模态对话框不显示关闭按钮 (x)

为什么在 jQuery 插件中返回 this.each(function())?

bootstrap 模式中的自动完成问题

jQuery 动画滚动

这些 jQuery 就绪函数之间有什么区别?

jQuery Keypress 箭头键

jQuery 插入 div 作为某个索引

jQuery 判断 是否存在并且有一个值

如何使用 jquery 动态更改 iframe 中的内容?

使用 jquery 通过文本设置下拉值

触发下拉更改事件

使用 jQuery 比较两个 Javascript 对象数组

PHPStorm IDE 中低效的 jQuery 使用警告

如何在调用 Ajax 等异步调用时让代码等待

Uncaught TypeError: undefined is not a function on loading jquery-min.js

如何淡出显示:inline-block

JQuery 判断 DOM 中的重复 id

Bootstrap:在 Modal 中打开另一个 Modal