首页 文章

检查用户是否已滚动到底部

提问于
浏览
572

我正在制作一个分页系统(有点像Facebook),当用户滚动到底部时,内容会加载 . 我想最好的方法是找到用户位于页面底部并运行ajax查询以加载更多帖子的时间 .

唯一的问题是我不知道如何检查用户是否已使用jQuery滚动到页面底部 . 有任何想法吗?

I need to find a way to check when the user has scrolled to the bottom of the page with jQuery.

21 回答

  • 10

    这是一个相当简单的方法:

    elm.onscroll = function() {
        if(elm.scrollTop + elm.clientHeight == elm.scrollHeight) //User has scrolled to the bottom of the element
    }
    
  • 909

    window 上使用.scroll()事件,如下所示:

    $(window).scroll(function() {
       if($(window).scrollTop() + $(window).height() == $(document).height()) {
           alert("bottom!");
       }
    });
    

    You can test it here,这会占据窗口的顶部滚动,因此它向下滚动多少,添加可见窗口的高度并检查它是否等于整个内容的高度( document ) . 如果你想检查用户是否接近底部,它看起来像这样:

    $(window).scroll(function() {
       if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
           alert("near bottom!");
       }
    });
    

    You can test that version here,只需将 100 调整为您想要触发的底部的任何像素 .

  • 8

    请检查this answer

    window.onscroll = function(ev) {
        if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
           console.log("bottom");
        }
    };
    

    您可以 footerHeight - document.body.offsetHeight 查看您是否靠近页脚或到达页脚

  • 0

    如果滚动到底端,请尝试匹配条件

    if ($(this)[0].scrollHeight - $(this).scrollTop() == 
        $(this).outerHeight()) {
    
        //code for your custom logic
    
    }
    
  • 44

    这是我的两分钱,因为接受的答案对我不起作用 .

    var documentAtBottom =(document.documentElement.scrollTop window.innerHeight)> = document.documentElement.scrollHeight;

  • 0

    对于那些使用Nick的解决方案并获得重复警报/事件触发的人,您可以在警报示例上方添加一行代码:

    $(window).scroll(function() {
       if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
           $(window).unbind('scroll');
           alert("near bottom!");
       }
    });
    

    这意味着代码只会在您第一次在文档底部的100px范围内时触发 . 如果您向上滚动然后向后滚动,它将不会重复,这可能会或可能没有用,这取决于您使用Nick的代码 .

  • 103

    尼克回答它的罚款,但你会在滚动时重复自己的功能,或者如果用户有窗口缩放则根本无法工作 . 我提出了一个简单的解决方法,只是math.round第一个高度,它的工作原理与假设一样 .

    if (Math.round($(window).scrollTop()) + $(window).innerHeight() == $(document).height()){
        loadPagination();
        $(".go-up").css("display","block").show("slow");
    }
    
  • 10

    要停止尼克的回答的反复警报

    ScrollActivate();
    
    function ScrollActivate() {
        $(window).on("scroll", function () {
            if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
                $(window).off("scroll");
                alert("near bottom!");
            }
        });
    }
    
  • 1

    您可以尝试以下代码,

    $("#dashboard-scroll").scroll(function(){
        var ele = document.getElementById('dashboard-scroll');
        if(ele.scrollHeight - ele.scrollTop === ele.clientHeight){
           console.log('at the bottom of the scroll');
        }
    });
    
  • 2

    我在普通js中的解决方案:

    let el=document.getElementById('el');
    el.addEventListener('scroll', function (e) {
    		if (el.scrollHeight - el.scrollTop - el.clientHeight<0) {
          console.log('Bottom')
        }
    });
    
    #el{
      width:300px;
      height:100px;
      overflow-y:scroll;
    }
    
    <div id="el">
    <div>content</div>
    <div>content</div>
    <div>content</div>
    <div>content</div>
    <div>content</div>
    <div>content</div>
    <div>content</div>
    <div>content</div>
    <div>content</div>
    <div>content</div>
    <div>content</div>
    </div>
    
  • 14

    除了Nick Craver的优秀接受答案之外,您可以限制滚动事件,以便不会频繁触发,因此 increasing browser performance

    var _throttleTimer = null;
    var _throttleDelay = 100;
    var $window = $(window);
    var $document = $(document);
    
    $document.ready(function () {
    
        $window
            .off('scroll', ScrollHandler)
            .on('scroll', ScrollHandler);
    
    });
    
    function ScrollHandler(e) {
        //throttle event:
        clearTimeout(_throttleTimer);
        _throttleTimer = setTimeout(function () {
            console.log('scroll');
    
            //do work
            if ($window.scrollTop() + $window.height() > $document.height() - 100) {
                alert("near bottom!");
            }
    
        }, _throttleDelay);
    }
    
  • 1

    所有这些解决方案对我和Firefox和Chrome都不起作用,所以我使用Miles O'Keefemeder omuraliev中的自定义函数,如下所示:

    function getDocHeight()
    {
        var D = document;
        return Math.max(
            D.body.scrollHeight, D.documentElement.scrollHeight,
            D.body.offsetHeight, D.documentElement.offsetHeight,
            D.body.clientHeight, D.documentElement.clientHeight
        );
    }
    
    function getWindowSize()
    {
      var myWidth = 0, myHeight = 0;
      if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
      } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
      } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
      }
      return [myWidth, myHeight];
    }
    
    $(window).scroll(function()
    {
        if($(window).scrollTop() + getWindowSize()[1] == getDocHeight())
        {
            alert("bottom!");
        }
    });
    
  • 0
    var elemScrolPosition = elem.scrollHeight - elem.scrollTop - elem.clientHeight;
    

    它计算距离滚动条到元素的底部 . 如果滚动条已到达底部,则等于0 .

  • 35

    Nick Craver的答案需要稍加修改才能在iOS 6 Safari Mobile上运行,应该是:

    $(window).scroll(function() {
       if($(window).scrollTop() + window.innerHeight == $(document).height()) {
           alert("bottom!");
       }
    });
    

    应该将 $(window).height() 更改为 window.innerHeight ,因为当地址栏被隐藏时,额外的60px会被添加到窗口的高度,但使用 $(window).height() 确实 not 会反映此更改,而使用 window.innerHeight 会这样做 .

    Notewindow.innerHeight 属性还包括水平滚动条的高度(如果它被渲染),与 $(window).height() 不同,它不包括水平滚动条的高度 . 这在Mobile Safari中不是问题,但可能会在其他浏览器或未来版本的Mobile Safari中导致意外行为 . 将 == 更改为 >= 可以解决大多数常见用例的问题 .

    了解有关 window.innerHeight 属性的更多信息here

  • 62

    让我在没有JQuery的情况下展示approch . 简单的JS功能:

    function isVisible(elem) {
      var coords = elem.getBoundingClientRect();
      var topVisible = coords.top > 0 && coords.top < 0;
      var bottomVisible = coords.bottom < shift && coords.bottom > 0;
      return topVisible || bottomVisible;
    }
    

    简短示例如何使用它:

    var img = document.getElementById("pic1");
        if (isVisible(img)) { img.style.opacity = "1.00";  }
    
  • 5

    这是我的两分钱:

    $('#container_element').scroll( function(){
            console.log($(this).scrollTop()+' + '+ $(this).height()+' = '+ ($(this).scrollTop() + $(this).height())   +' _ '+ $(this)[0].scrollHeight  );
            if($(this).scrollTop() + $(this).height() == $(this)[0].scrollHeight){
                console.log('bottom found');
            }
        });
    
  • 17

    Pure JScross-browserdebouncing (相当不错 performance

    var CheckIfScrollBottom = debouncer(function() {
        if(getDocHeight() == getScrollXY()[1] + window.innerHeight) {
           console.log('Bottom!');
        }
    },500);
    
    document.addEventListener('scroll',CheckIfScrollBottom);
    
    function debouncer(a,b,c){var d;return function(){var e=this,f=arguments,g=function(){d=null,c||a.apply(e,f)},h=c&&!d;clearTimeout(d),d=setTimeout(g,b),h&&a.apply(e,f)}}
    function getScrollXY(){var a=0,b=0;return"number"==typeof window.pageYOffset?(b=window.pageYOffset,a=window.pageXOffset):document.body&&(document.body.scrollLeft||document.body.scrollTop)?(b=document.body.scrollTop,a=document.body.scrollLeft):document.documentElement&&(document.documentElement.scrollLeft||document.documentElement.scrollTop)&&(b=document.documentElement.scrollTop,a=document.documentElement.scrollLeft),[a,b]}
    function getDocHeight(){var a=document;return Math.max(a.body.scrollHeight,a.documentElement.scrollHeight,a.body.offsetHeight,a.documentElement.offsetHeight,a.body.clientHeight,a.documentElement.clientHeight)}
    

    Demo : http://jsbin.com/geherovena/edit?js,output

    PS: DebouncergetScrollXYgetDocHeight 不是我写的

    我只是展示它的工作方式,以及我将如何做

  • 0

    我使用@ddanone answear并添加了Ajax调用 .

    $('#mydiv').on('scroll', function(){
      function infiniScroll(this);
    });
    
    function infiniScroll(mydiv){
    console.log($(mydiv).scrollTop()+' + '+ $(mydiv).height()+' = '+ ($(mydiv).scrollTop() + $(mydiv).height())   +' _ '+ $(mydiv)[0].scrollHeight  );
    
    if($(mydiv).scrollTop() + $(mydiv).height() == $(mydiv)[0].scrollHeight){
        console.log('bottom found');
        if(!$.active){ //if there is no ajax call active ( last ajax call waiting for results ) do again my ajax call
            myAjaxCall();
        }
    }
    

    }

  • 2

    尼克克拉弗的答案很好,不用担心 $(document).height() 的值因浏览器而异 .

    要使其适用于所有浏览器,请使用James Padolsey中的此功能:

    function getDocHeight() {
        var D = document;
        return Math.max(
            D.body.scrollHeight, D.documentElement.scrollHeight,
            D.body.offsetHeight, D.documentElement.offsetHeight,
            D.body.clientHeight, D.documentElement.clientHeight
        );
    }
    

    代替 $(document).height() ,以便最终代码为:

    $(window).scroll(function() {
           if($(window).scrollTop() + $(window).height() == getDocHeight()) {
               alert("bottom!");
           }
       });
    
  • 2

    我不确定为什么还没有发布,但根据the documentation from MDN,最简单的方法是使用本机javascript属性:

    element.scrollHeight - element.scrollTop === element.clientHeight
    

    当您位于任何可滚动元素的底部时,返回true . 所以简单地使用javascript:

    element.addEventListener('scroll', function(event)
    {
        var element = event.target;
        if (element.scrollHeight - element.scrollTop === element.clientHeight)
        {
            console.log('scrolled');
        }
    });
    

    scrollHeight 在浏览器中有广泛的支持,从8到更精确,而 clientHeightscrollTop 都得到大家的支持 . 即使是6.这应该是跨浏览器安全的 .

  • 39

    这是一段代码,可以帮助您调试代码,我测试了上面的答案,发现它们是错误的 . 我在Chrome,IE,Firefox,iPad(Safari)上测试了以下内容 . 我没有安装任何其他测试...

    <script type="text/javascript">
       $(function() {
          $(window).scroll(function () {
             var docElement = $(document)[0].documentElement;
             var winElement = $(window)[0];
    
             if ((docElement.scrollHeight - winElement.innerHeight) == winElement.pageYOffset) {
                alert('bottom');
             }
          });
       });
    </script>
    

    可能有一个更简单的解决方案,但我停在 IT WORKED

    如果你仍然遇到一些流氓浏览器的问题,这里有一些代码可以帮助你调试:

    <script type="text/javascript">
       $(function() {
          $(window).scroll(function () {
             var docElement = $(document)[0].documentElement;
             var details = "";
             details += '<b>Document</b>
    '; details += 'clientHeight:' + docElement.clientHeight + '
    '; details += 'clientTop:' + docElement.clientTop + '
    '; details += 'offsetHeight:' + docElement.offsetHeight + '
    '; details += 'offsetParent:' + (docElement.offsetParent == null) + '
    '; details += 'scrollHeight:' + docElement.scrollHeight + '
    '; details += 'scrollTop:' + docElement.scrollTop + '
    '; var winElement = $(window)[0]; details += '<b>Window</b>
    '; details += 'innerHeight:' + winElement.innerHeight + '
    '; details += 'outerHeight:' + winElement.outerHeight + '
    '; details += 'pageYOffset:' + winElement.pageYOffset + '
    '; details += 'screenTop:' + winElement.screenTop + '
    '; details += 'screenY:' + winElement.screenY + '
    '; details += 'scrollY:' + winElement.scrollY + '
    '; details += '<b>End of page</b>
    '; details += 'Test:' + (docElement.scrollHeight - winElement.innerHeight) + '=' + winElement.pageYOffset + '
    '; details += 'End of Page? '; if ((docElement.scrollHeight - winElement.innerHeight) == winElement.pageYOffset) { details += 'YES'; } else { details += 'NO'; } $('#test').html(details); }); }); </script> <div id="test" style="position: fixed; left:0; top: 0; z-index: 9999; background-color: #FFFFFF;">

    我希望这能节省一些时间 .

相关问题