Get percentage of scroll position

2020-03-07 07:55发布

问题:

The problem:

What would be the mathematical formula to calculate (regardless of the scrollHeight of the document) how far the bottom of the scrollbar is from it's total bottom (which would be the end of the page). So, for example, when the scrollbar is at the top, I would say the distance in percentages of the bottom of it, from the bottom of the document, would be 0%, and when it's totally scrolled all the way (vertically), it would be 100%.

My goal:

My goal is to calculate how many pixels there are between the bottom and a specific position which is, let's say 3%, relative to the viewport, above that bottom. Again, the document height should mean nothing. 3% are 3% if it's relative to the viewport.

Known variables:

var P              = 3 // in %
var totalHeight    = document.documentElement.scrollHeight;
var viewportHeight = document.documentElement.clientHeight;

回答1:

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

document.onscroll = function(){ 
  var pos = showPosition(document.body);
  console.clear();
  console.log( Math.round(pos) + '%' )
};

function showPosition(elm){
    var parent = elm.parentNode,
        pos = (elm.scrollTop || parent.scrollTop) / (parent.scrollHeight - parent.clientHeight ) * 100;
    
    return pos;   
};
body{ height:2000px; }


● Different between scrollHeight & clientHeight



回答2:

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/