计算滚动条距底部多远(距离底部的百分比)
  62hBwnF7hQwr 2023年11月02日 29 0

计算页面某个容器内滚动条距离

// 获取某固定元素滚动的高度
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;

}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

62hBwnF7hQwr