문제

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