How to get maximum document scrolltop value

雨燕双飞 提交于 2019-11-29 01:27:44

The code in your comments should work:

$(document).height() - $(window).height()

Here's an example that alerts when you scroll to the maximum scroll position: http://jsfiddle.net/DWn7Z/

If you want to "guess" the maximum scrolltop value, maybe you should compare the height of the document and the viewport height (size of your window).

/**
 * Return a viewport object (width and height)
 */
function viewport()
{
    var e = window, a = 'inner';
    if (!('innerWidth' in window))
    {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }
}

// Retrieve the height of the document, including padding, margin and border
var documentHeight = $(document).outerheight(true);
var viewPortData = viewport();

var maxScrollTop = documentHeight - viewPortData.height;

Of course, in your plugin, you should also add a listener on the resize event, and re-calculate the maximum scrollTop.

In vanilla Javascript I'm currently doing this:

getScrollTopMax = function () {
  var ref;
  return (ref = document.scrollingElement.scrollTopMax) != null
      ? ref
      : (document.scrollingElement.scrollHeight - document.documentElement.clientHeight);
};

This returns Gecko's non-standard scrollTopMax if it exists, otherwise calculates it. I'm using document.scrollingElement here, which only exists on particular browsers, but it's easy to polyfill.

Here is an answer i wrote https://stackoverflow.com/a/48246003/7668448, it's about a polyfill for scrollTopMax which is a native property for Element objects. (only mozilla). Look at the response, you can really like it.

Bellow just a quick snippet. The answer in the link is more rich (make sure to look).

(function(elmProto){
    if ('scrollTopMax' in elmProto) {
        return;
    }
    Object.defineProperties(elmProto, {
        'scrollTopMax': {
            get: function scrollTopMax() {
              return this.scrollHeight - this.clientTop;
            }
        },
        'scrollLeftMax': {
            get: function scrollLeftMax() {
              return this.scrollWidth - this.clientLeft;
            }
        }
    });
}
)(Element.prototype);

use example:

var el = document.getElementById('el1');
var max = el.scrollLeftMax; 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!