Get percentage of scroll position

前端 未结 2 1579
时光说笑
时光说笑 2021-01-07 11:59

The problem:

What would be the mathematical formula to calculate (regardless of the scrollHeight of the document) how far the bottom of the scrollbar i

2条回答
  •  不思量自难忘°
    2021-01-07 12:26

    When you scroll to the bottom, the final position value is equal to the height of your document minus the height of one screen (viewport). So if you compute:

    scrollPositionRelative = scrollPosition / (documentHeight - viewportHeight);
    

    The values will be in the range 0-1 as expected.

    Here's the function used in the example given at the end.

    function getScrollPosition () {
      var viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); // Viewport height (px)
      var scrollPosition = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; // Current scroll position (px)
      var documentHeight = $(document).height(); // Document height (px)
      var scrollPositionRelative = scrollPosition / (documentHeight - viewportHeight); // The document height is reduced by the height of the viewport so that we reach 100% at the bottom
      return {
        documentHeight: documentHeight,
        relative: scrollPositionRelative,
        absolute: scrollPositionRelative * documentHeight // Yields an "average" pixel position
      };
    }
    

    See it in action: http://jsbin.com/tawana/1/

提交回复
热议问题