Even simplest .scrollTop() example returns 0

穿精又带淫゛_ 提交于 2019-12-23 06:10:35

问题


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:

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

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

I guess I can make this work with this:

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

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


回答1:


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.



来源:https://stackoverflow.com/questions/20792809/even-simplest-scrolltop-example-returns-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!