Get percentage of scroll position

巧了我就是萌 提交于 2020-02-14 02:22:47

问题


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/



来源:https://stackoverflow.com/questions/28677335/get-percentage-of-scroll-position

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