How to get the number of pixels a user has scrolle

2019-02-21 14:00发布

问题:

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:

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



回答4:

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>