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

有些话、适合烂在心里 提交于 2019-12-19 12:37:10

问题


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

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


回答1:


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

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

See also this question.




回答2:


In pure javascript you can simply do like that:

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

More infos (The Mozilla Developer Network) :

  • onscroll
  • scrollY



回答3:


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

    <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>



回答4:


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



来源:https://stackoverflow.com/questions/4081064/how-to-get-the-number-of-pixels-a-user-has-scrolled-down-the-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!