Javascript 如何获取用户向下滚动页面的像素数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4081064/
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-23 10:30:44  来源:igfitidea点击:

How to get the number of pixels a user has scrolled down the page?

javascriptjqueryscrollbar

提问by gadlol

Suppose we have a html page with large height.So there will be a vertical scrollbar.

假设我们有一个高度很大的html页面,那么就会有一个垂直滚动条。

As the user scrolls down I want to know how much he has scrolled using javascript (jquery) I suppose... Is this possible?

当用户向下滚动时,我想知道他使用 javascript (jquery) 滚动了多少……这可能吗?

回答by Fabien Sa

In pure javascript you can simply do like that:

在纯 javascript 中,您可以简单地这样做:

window.onscroll = function (e) {
    console.log(window.scrollY); // Value of scroll Y in px
};

More infos (The Mozilla Developer Network) :

更多信息(Mozilla 开发者网络):

回答by justkt

You can do this using .scroll()and .scrollTop().

你可以使用.scroll().scrollTop()来做到这一点。

 $(window).scroll(function() {
     // use the value from $(window).scrollTop(); 
 });

See also this question.

另请参阅此问题

回答by Four.Twenty

This is what i used on my website... when anyone scrolls 620 pixels down the menu will pop up, I input the numbers manually. I'm still a noob at javascript but I hope this helps

这是我在我的网站上使用的...当任何人向下滚动 620 像素时,菜单会弹出,我手动输入数字。我仍然是 javascript 的菜鸟,但我希望这会有所帮助

    <script>
    $(document).ready(function(){
        $(window).scroll(function(){
            var scrollTop = 620;
            if($(window).scrollTop() >= scrollTop){
                $('.Nav').css({
                    position : 'fixed',
                    top : '0'
                });
            }
            if($(window).scrollTop() < scrollTop){
                $('.Nav').removeAttr('style');  
            }
        })
    })
    </script>

回答by Frédéric Hamidi

Yes. See scrollTop()in jQuery, which wraps the scrollTopDOM property.

是的。请参阅jQuery 中的scrollTop(),它包装了scrollTopDOM 属性。