要获取当前的滚动比率,您应该首先检查您的文档是否有一个 scrollableHeight。在这种特殊情况下,我选择了返回0
。接下来的计算同上。
/**
* @returns number
*/
function scrollYProgression() {
const scrollableHeight = window.document.body.scrollHeight - window.innerHeight;
if (scrollableHeight <= 0) return 0;
return window.scrollY / scrollableHeight;
}
与jQuery捆绑在一起:
$(window).scroll(() => {
$('#progressbar')
.attr('value', scrollYProgression() * 100);
});
收听滚动事件时要小心!这可能真的很重,每次重绘你真的需要它最多一次。您可以检查window.requestAnimationFrame
以防止对您的方法进行大量调用(最大 60/s)。
关于滚动事件监听器:http: //www.html5rocks.com/en/tutorials/speed/animations
编辑:
没有 jQuery 并使用window.requestAnimationFrame
将触发速率限制为 60/s
/** @return number */
function scrollYProgression() {
const scrollableHeight = window.document.body.scrollHeight - window.innerHeight;
if (scrollableHeight <= 0) return 0;
return window.scrollY / scrollableHeight;
}
/**
* @return void
* @description DOM element manipulation
*/
function scrollHandler() {
const progress = scrollYProgression();
const bar = document.getElementById('progressbar');
bar.setAttribute('value', progress * 100);
}
/** Start listening */
window.addEventListener('scroll', function(ev){
window.requestAnimationFrame(scrollHandler);
}, { passive: true });