Get percentage of scroll position

前端 未结 2 1566
时光说笑
时光说笑 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:24

    Returns a number between 0 to 100 relative to scroll position:

    document.onscroll = function(){ 
      var pos = getVerticalScrollPercentage(document.body)
      document.body.innerHTML = "<span>" + Math.round(pos) + "%<span>"
    }
    
    function getVerticalScrollPercentage( elm ){
      var p = elm.parentNode
      return (elm.scrollTop || p.scrollTop) / (p.scrollHeight - p.clientHeight ) * 100
    }
    body{ height:2000px }
    span{ position:fixed; font:5em Arial; color:salmon; }


    ● Difference between scrollHeight & clientHeight

    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题