获取滚动位置的百分比

Get percentage of scroll position

本文关键字:百分比 位置 滚动 获取      更新时间:2024-03-20

问题:

要计算的数学公式是什么(不管文档的scrollHeight)滚动条的底部离它的总底部(将是页面的末尾)有多远。因此,例如,当滚动条位于顶部时,我会说它底部与文档底部的距离(以百分比计)为0%,当它完全滚动(垂直)时,它将为100%

我的目标:

我的目标是计算底部和特定位置之间有多少像素,比如说,相对于视口,底部上方的3%。同样,文档高度应该毫无意义。如果3%是相对于视口的,则为3%。

已知变量:

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

返回相对于滚动位置介于0100之间的数字:

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; }


scrollHeight&clientHeight

滚动到底部时,最终位置值等于文档的高度减去一个屏幕(视口)的高度。所以如果你计算:

scrollPositionRelative = scrollPosition / (documentHeight - viewportHeight);

这些值将在预期的0-1范围内。

下面是最后给出的示例中使用的函数。

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
  };
}

在行动中看到它:http://jsbin.com/tawana/1/