Get scroll position using jquery

前端 未结 4 877
一向
一向 2020-12-24 01:29

Strange request, but I need to get the current browser scroll position as a variable. What js or jquery function should I use? I need it to figure out what elements to displ

相关标签:
4条回答
  • 2020-12-24 02:01

    cross browser variant

    $(document).scrollTop();
    
    0 讨论(0)
  • 2020-12-24 02:01

    Older IE and Firefox browsers attach the scrollbar to the documentElement, or what would be the <html> tag in HTML.

    All other browsers attach the scrollbar to document.body, or what would be the <body> tag in HTML.

    The correct solution would be to check which one to use, depending on browser

    var doc = document.documentElement.clientHeight ? document.documentElement : document.body;
    var s   = $(doc).scrollTop();
    

    jQuery does make this a little easier, when passing in either window or document jQuery's scrollTop does a similar check and figures it out, so either of these should work cross-browser

    var s = $(document).scrollTop();
    

    or

    var s = $(window).scrollTop();
    

    jQuery scrollTop() docs

    Description: Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.


    ...nothing that works for my div, just the full page

    If it's for a DIV, you'd have to target the element that has the scrollbar attached, to get the scrolled amount

    $('div').scrollTop();
    

    If you need to get the elements distance from the top of the document, you can also do

    $('div').offset().top
    
    0 讨论(0)
  • 2020-12-24 02:02

    Use scrollTop() to get or set the scroll position.

    0 讨论(0)
  • 2020-12-24 02:17

    I believe the best method with jQuery is using .scrollTop():

    var pos = $('body').scrollTop();
    
    0 讨论(0)
提交回复
热议问题