JQuery Detect Scroll at Bottom

后端 未结 10 850
南方客
南方客 2021-01-30 09:58

I wish to achieve content load when the user scrolls to the bottom of the page.

I am having a problem. It works fine on desktop browsers but not on mobile. I have imple

10条回答
  •  悲&欢浪女
    2021-01-30 10:11

    Here is an aggregate of the other answers which works very well for me. It could be written as a jQuery plugin sometime.

    // Handles scrolling past the window up or down to refresh or load more data.
    var scrolledPastTop = false;
    var scrolledPastBottom = false;
    var scrollPrevious = 0;
    
    function getDocumentHeight() {
      return Math.max(
          Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
          Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
          Math.max(document.body.clientHeight, document.documentElement.clientHeight)
      );
    }
    
    function bottomScrollRefresh(callback) {
      var pastBottom = $window.height() + $window.scrollTop() > getDocumentHeight();
      if(!scrolledPastBottom && pastBottom) {
        callback($window.height() + $window.scrollTop());
        scrolledPastBottom = true;
      } else {
        if(!pastBottom) scrolledPastBottom = false;
      }
      scrollPrevious = $window.scrollTop();
    }
    
    function topScrollRefresh(callback) {
      var pastTop = $window.scrollTop() < scrollPrevious && $window.scrollTop() <= 0;
      if(!scrolledPastTop && pastTop) {
        callback($window.scrollTop());
        scrolledPastTop = true;
      } else {
        if(!pastTop) scrolledPastTop = false;
      }
      scrollPrevious = $window.scrollTop();
    }
    

    To use this in your code, add something like this:

    window.onscroll = function() {
      topScrollRefresh(function(pos) {
          console.log("Loading top. " + pos);
      });
      bottomScrollRefresh(function(pos) {
        console.log("Loading bottom. " + pos);
      });
    };
    

    Works great for my PhoneGap/Cordova app.

提交回复
热议问题