最终效果:

代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
*{margin:0;padding:0;}
.box{height:3000px;width:100%;background:#ccc;}
.progress{position:fixed;top:0;height:5px;background:red;}
</style>
<title>原生js页面滚动顶部显示滚动总进度条效果</title>
</head>
<body>
<div class="progress"></div>
<div>
<div class="box">1</div>
</div>
</body>
<script>
(function(){
let pageHeight = document.body.scrollHeight || document.documentElement.scrollHeight; // 页面总高度
let windowHeight = document.documentElement.clientHeight || document.body.clientHeight; // 浏览器视口高度
let scrollAvail = pageHeight - windowHeight; // 可滚动的高度
console.log('可滚动的高度:', scrollAvail);
window.onscroll = function () {
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // 获取滚动条的高度
console.log('滚动条的高度:', scrollTop);
document.querySelector('.progress').style.width = (scrollTop/scrollAvail)*100 + '%'; // 计算占比
};
}());
</script>
</html>

本文介绍如何使用原生JavaScript结合HTML和CSS创建一个页面滚动进度条,该进度条能够实时显示用户在页面上的滚动位置,通过计算滚动条高度与可滚动高度的比例来更新进度条宽度。
1万+

被折叠的 条评论
为什么被折叠?



