How to get maximum document scrolltop value

前端 未结 4 823
执笔经年
执笔经年 2020-12-15 20:12

I am making some plugin and I need to get maximum scrollTop value of the document. Maximum scrollTop value is 2001 , but $(docum

相关标签:
4条回答
  • 2020-12-15 20:25

    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.

    0 讨论(0)
  • 2020-12-15 20:41

    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.

    0 讨论(0)
  • 2020-12-15 20:42

    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/

    0 讨论(0)
  • 2020-12-15 20:47

    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; 
    
    0 讨论(0)
提交回复
热议问题