質問

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.

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top