js:监听页面滚动scroll,实现阅读进度条

举报
彭世瑜 发表于 2022/09/25 06:38:24 2022/09/25
1.7k+ 0 0
【摘要】 实现原理 // 距顶部 var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // 可视区高度...

实现原理


// 距顶部
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;

// 可视区高度
var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;

// 滚动条总高度
var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
// 滚动到顶部
scrollTop == 0

// 滚动到底部
scrollTop == scrollHeight - clientHeight

  
 

index.html

<link rel="stylesheet" href="./style.css" />

    <!-- 进度条 -->
    <div class="progress-bar-wrap">
      <div class="progress-bar"></div>
    </div>

<script src="./script.js"></script>

  
 

style.css

body {
  height: 200vh;
}

.progress-bar-wrap {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background-color: #ddd;
}

.progress-bar {
  position: absolute;
  left: 0;
  height: 100%;
  content: "";
  background-color: #0089f2;
}
  
 

script.js

(function () {
  let progressBar = document.querySelector(".progress-bar");
  
  document.addEventListener("scroll", function (e) {
    // 距顶部
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    // 可视区高度
    var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
    // 滚动条总高度
    var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;

    console.log(scrollTop, scrollHeight, clientHeight);

    progressBar.style.width =
      +(scrollTop / (scrollHeight - clientHeight)).toFixed(2) * 100 + "%";
  });
})();
  
 

在线体验: https://mouday.github.io/front-end-demo/progress-bar/index.html

参考
CSS实现阮大佬博文的阅读进度功能

文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。

原文链接:pengshiyu.blog.csdn.net/article/details/126987435

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。