0

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

 1 year ago
source link: https://blog.51cto.com/u_13567403/5702569
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

精选 原创

彭世瑜 2022-09-22 10:41:17 ©著作权

文章标签 html css github 文章分类 Go语言 编程语言 yyds干货盘点 阅读数183


// 距顶部
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实现阮大佬博文的阅读进度功能

  • 打赏
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK