计算页面某个容器内滚动条距离
// 获取某固定元素滚动的高度
const scrollHeight = document.getElementById('mobileRenderContent').scrollHeight;
// 获取当前窗口大小,滚动条不一定从顶部开始计算,因此287是距离顶部的位置,如果没有就写0
const windowHeight = (document.documentElement.clientHeight || document.body.clientHeight) - 287;
const scrollTop = document.getElementById('mobileRenderContent').scrollTop; // 滚动条距离顶部高度
const scrollBottom = scrollHeight - windowHeight - scrollTop; // 滚动条距离底部高度
计算全窗口内滚动条距离
// 需求可能是全窗口,那么scrollHeight可以直接这样写:
const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
const windowHeight = (document.documentElement.clientHeight || document.body.clientHeight);
const scrollBottom = scrollHeight - windowHeight - scrollTop; // 滚动条距离底部高度
监听滚动条写法
window.addEventListener('resize', () => {
// 监听页面大小变化
});
window.addEventListener("scroll", ()=>{
//监听页面滚动
}, false);
计算滚动条距离底部百分比
// if语句作用:滚动后再此滚动时,如果已存的值比滚动的值大,就不保存,否则会有BUG,阅读百分比会一会多一会小,实际只能增大不能减少
if (((scrollHeight - scrollBottom) / scrollHeight) * 100 > this.percent) {
this.percent = ((scrollHeight - scrollBottom) / scrollHeight) * 100;
}