我正在使用以下行计算页面上的滚动进度(向下滚动后隐藏在 View 中的文档百分比):
window.pageYOffset / document.body.scrollHeight
这适用于大多数网站。但是一些网站调整了滚动或溢出属性,实际上破坏了上述计算。
例如,on this page上面的行将始终返回 0
。
有没有更好的方法来计算在这种情况下适用的滚动进度?
最佳答案
这是我的方法:
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
let limit = Math.max( document.body.scrollHeight, document.body.offsetHeight,
document.documentElement.clientHeight, document.documentElement.scrollHeight,
document.documentElement.offsetHeight );
let footerHeight = document.querySelector('footer').offsetHeight;
let max = limit - window.innerHeight - footerHeight;
let height = window.pageYOffset / max * 100;
height = Math.min(100, Math.max(0, height));
const loader = document.getElementById("loader-scroll");
loader.style.width = 0 + height + "%";
}
它适用于大多数浏览器
关于javascript - 如何计算防弹滚动进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21703587/