How do I get the browser scroll position in jQuery?

前端 未结 3 708
长情又很酷
长情又很酷 2020-12-24 10:24

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

相关标签:
3条回答
  • 2020-12-24 10:47

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

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

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

    0 讨论(0)
  • 2020-12-24 10:53

    It's better to use $(window).scroll() rather than $('#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.

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

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

    $('#Eframe').scroll(function(){
        var scrollPos = $('#Eframe').scrollTop();
        console.log(scrollPos);
    });
    
    0 讨论(0)
  • 2020-12-24 11:02

    Pure javascript can do!

    var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    
    0 讨论(0)
提交回复
热议问题