Can you get the user’s scroll position every time they scroll with JavaScript/jQuery?
Is it possible to grab the current position of the users scroll bar when they scroll?
Say, if they were scrolled to the very top it would be 0, if they scrolled down it'd change.
Can I assign a var开发者_如何转开发iable to contain the current scroll position whenever I access it, or is there a function in JavaScript for this already?
From your comment, I get you are looking for a scroll event listener such as http://api.jquery.com/scroll/, and then you can use http://api.jquery.com/scrollTop/ to find out the position of the scroll.
For example:
<script>
$(window).scroll(function () {
//You've scrolled this much:
$('p').text("You've scrolled " + $(window).scrollTop() + " pixels");
});
</script>
http://jsfiddle.net/pFaTF/
There are properties on the window
object for this: window.scrollX
and window.scrollY
.
See e.g. http://javascript.gakaa.com/window-scrollx-2-0-scrolly.aspx
You can get the scrollTop property of the body element:
document.getElementsByTagName('body')[0].scrollTop;
This returns the number of pixels that are above the visible area.So 0 when the user hasn't scrolled, bodyheight-viewporthieght
when the scrollbar is at the bottom.
Try using .scrollTop()
Here is an example:
http://jsfiddle.net/LZM7H/
Edit
If you are trying to output the position of the element being scrolled as it happens then this can be achieved using the .scroll() event:
$('#container').scroll(function(){
var position = $('#container').scrollTop();
});
Here is a live example:
http://jsfiddle.net/LZM7H/2/
as additional to Paul D Waite answer, you can told the browser to scroll the window to by using window.scroll(0,0);
, where the value is referencing to x and y position.
精彩评论