获取滚动位置的百分比
Get percentage of scroll position
问题:
要计算的数学公式是什么(不管文档的scrollHeight
)滚动条的底部离它的总底部(将是页面的末尾)有多远。因此,例如,当滚动条位于顶部时,我会说它底部与文档底部的距离(以百分比计)为0%,当它完全滚动(垂直)时,它将为100%。
我的目标:
我的目标是计算底部和特定位置之间有多少像素,比如说,相对于视口,底部上方的3%。同样,文档高度应该毫无意义。如果3%是相对于视口的,则为3%。
已知变量:
var P = 3 // in %
var totalHeight = document.documentElement.scrollHeight;
var viewportHeight = document.documentElement.clientHeight;
返回相对于滚动位置介于0
到100
之间的数字:
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/
相关文章:
- jquery试图按名称获取按钮位置
- 我可以获得相对于被点击元素的确切点击位置吗
- 谷歌地图固定位置覆盖
- 在单击任何位置时隐藏元素,而不检查每次DOM单击
- 循环比赛位置算法
- es6 相当于下划线查找位置
- jQuery循环在特定位置暂停
- 如何将CSS背景位置属性从百分比转换为像素
- 当前光标位置(百分比)
- 获取滚动位置的百分比
- 固定位置高度比浏览器窗口大百分比
- jQuery使用calc作为值(从百分比中减去px)对位置进行动画处理
- 位置为的屏幕的CSS百分比:绝对值
- 将圆内的点位置表示为任意线段的百分比
- 有百分比宽度的位置固定元件可以从体宽计算吗?
- 检测用户点击的水平位置的百分比
- 计算颜色HEX有2种颜色和百分比/位置
- Rapahel js paper.print(),位置以百分比形式指定
- 在javascript中,取顶部和左侧的位置并转换为百分比
- 获取光标位置(以百分比表示)