How do I get the browser scroll position in jQuery?

I have a web document with scroll. I want to get the value, in pixels, of the current scroll position. When I run the below function it returns the value zero. How can I do this?

<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript" src="js/jquery.mousewheel.min.js"></script>
<script type="text/javascript">
$(function (){
$('#Eframe').on("mousewheel", function() {
alert(document.body.scrollDown)
}
})
</script>
190944 次浏览

Since it appears you are using jQuery, here is a jQuery solution.

$(function() {
$('#Eframe').on("mousewheel", function() {
alert($(document).scrollTop());
});
});

Not much to explain here. If you want, here is the jQuery documentation.

It's better to use $(window).scroll() rather than $('#Eframe').on("mousewheel")

$('#Eframe').on("mousewheel") will not trigger if people manually scroll using up and down arrows on the scroll bar or grabbing and dragging the scroll bar itself.

$(window).scroll(function(){
var scrollPos = $(document).scrollTop();
console.log(scrollPos);
});

If #Eframe is an element with overflow:scroll on it and you want it's scroll position. I think this should work (I haven't tested it though).

$('#Eframe').scroll(function(){
var scrollPos = $('#Eframe').scrollTop();
console.log(scrollPos);
});

Pure javascript can do!

var scrollTop = window.pageYOffset || document.documentElement.scrollTop;