即使是最简单的.scrollTop()示例也会返回0 [英] Even simplest .scrollTop() example returns 0

查看:78
本文介绍了即使是最简单的.scrollTop()示例也会返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到元素相对于视口的垂直位置。我发现jquery .scrollTop()函数就是这个,但它返回0.它确实在检查$(document)的scrollTop时返回正确的值,但是我需要元素的位置,而不是窗口位置。我做错了什么?

I need to find vertical position of element relative to viewport. I found that jquery .scrollTop() function is for this, but it returns 0. It does return correct value when checking $(document)'s scrollTop instead, but I need element's position, not window position. Am I doing something wrong?

HTML:

1<br>
<span>2</span>
<div style="height:10000px"></div>

JavaScript:

JavaScript:

$(window).scroll(function() {
    console.log($("span").scrollTop())
})

Jsfiddle: http:// jsfiddle。 net / kwVC7 /

Jsfiddle: http://jsfiddle.net/kwVC7/

我想我可以用这个工作:

I guess I can make this work with this:

$("span").offset().top - $(document).scrollTop()

但我仍然感兴趣的是为什么element.scrollTop不能正常工作。

but still I'm interested why element.scrollTop does not work as is supposed.

推荐答案

它正在返回正确的值。正如我在上面的评论中所指出的, .scrollTop()用于检索滚动条的位置匹配元素...它与检索匹配元素相对于视口的位置无关。

It is returning the correct value. As I noted in my comment above, .scrollTop() is for retrieving the position of the scroll bar for the matched element... It has nothing to do with retrieving the position of the matched element in relation to the viewport.

这篇关于即使是最简单的.scrollTop()示例也会返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆