简体   繁体   English

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

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

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) 滚动了多少……这可能吗?

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 开发者网络):

You can do this using .scroll() and .scrollTop() .你可以使用.scroll().scrollTop()来做到这一点。

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

See also this question .另请参阅此问题

This is what i used on my website... when anyone scrolls 620 pixels down the menu will pop up, I input the numbers manually.这是我在我的网站上使用的...当任何人向下滚动 620 像素时,菜单会弹出,我手动输入数字。 I'm still a noob at javascript but I hope this helps我仍然是 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>

Yes.是的。 See scrollTop() in jQuery, which wraps the scrollTop DOM property.请参阅 jQuery 中的scrollTop() ,它包装了scrollTop DOM 属性。

You can use window.scrollX to detect how much pixels the user has scrolled right.您可以使用window.scrollX来检测用户向右滚动了多少像素。
You can use window.scrollY to detect how much pixels the user has scrolled down.您可以使用window.scrollY来检测用户向下滚动了多少像素。
You can use window.scrollTo(x, y);您可以使用window.scrollTo(x, y); to set scroll pixels right (x) and down (y).向右 (x) 和向下 (y) 设置滚动像素。


Example code: 示例代码:

 var x = window.scrollX, y = window.scrollY; window.scrollTo(0, 200);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM