Javascript 如何在 jQuery 中获取浏览器滚动位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10615845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:10:09  来源:igfitidea点击:

How do I get the browser scroll position in jQuery?

javascriptjquery

提问by Carlos

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>

回答by

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

由于看起来您正在使用 jQuery,这里是一个 jQuery 解决方案。

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

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

这里不多解释。如果需要,这里是jQuery 文档

回答by Daniel Tonon

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

最好使用$(window).scroll()而不是$('#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.

$('#Eframe').on("mousewheel")如果人们使用滚动条上的向上和向下箭头手动滚动或抓取并拖动滚动条本身,则不会触发。

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

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

如果#Eframe是一个元素,overflow:scroll并且你想要它的滚动位置。我认为这应该有效(不过我还没有测试过)。

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

回答by Amos

Pure javascript can do!

纯javascript可以做到!

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