Domanda

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.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top