# JavaScript通过onscroll实现页面顶部进度条效果

> 当我们获取页面内容高度、窗口可视高度及其可滚动高度值时，当页面的滚动条滚动时,我们可以通过该事件实现页面滚动进度条效果。

Author: DeathGhost
Published: 2019-05-20 23:26:23
Category: javascript
Canonical: https://www.deathghost.cn/article/javascript/47
Keywords: 滚动条, 进度条, JavaScript滚动事件, 页面进度条, 滚动条占比, 进度条占比, 滚动条监听, onscroll, onresize, 特效

无意中浏览网页看到在鼠标向下滑动页面时，页面顶部以进度条的方式展示效果，在这里记录下自己玩玩。

使用场景：页面头部（header）绝对定位（absolute 或 fixed）或粘性定位（sticky）悬浮或固定的情况下，通过CSS渲染其展示效果，一定程度改善用户体验效果。

实现方法：首先获取三个值：页面总高度、可视高度及其可滚动高度，通过onscroll事件执行样式即可。

![JavaScript页面滚动进度条](https://www.deathghost.cn/public/upload/article/2019/05/1558365907811.jpg)

JavaScript页面滚动进度条效果

获取相关参数值：

let pageHeight = document.body.scrollHeight || document.documentElement.scrollHeight;
let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
let scrollAvail = pageHeight - windowHeight;
在顶部区域需要展示的地方定义标签样式。e.g .

在所要展示的地方定义标签，绑定CSS，设置高度一定值，默认宽度为0即可

下面是PUG,SCSS写法演示

div.scrollBar
.scrollBar{
  position: absolute;
  left:0;
  bottom:0;
  background-color:rgba($color: #0084ff, $alpha: .25);
  width:0;
  height:2px;
}
然后我们在JavaScript中执行方法即可

标签元素宽度在滚动事件触发时 = (滚动条高度/可滚动高度)*100   '%';
function scrollBar() {
  let pageHeight = document.body.scrollHeight || document.documentElement.scrollHeight;
  let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
  let scrollAvail = pageHeight - windowHeight;
  window.onscroll = function () {
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      document.querySelector('.scrollBar').style.width = (scrollTop/scrollAvail)*100   '%';
  };
}
另外，浏览器窗口变更时，我们可以通过onresize属性resize事件去再次执行它，以免溢出。

window.onresize = () => scrollBar();
最终完整的如下：

scrollBar();
window.onresize = () => scrollBar();
function scrollBar() {
  let pageHeight = document.body.scrollHeight || document.documentElement.scrollHeight;
  let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
  let scrollAvail = pageHeight - windowHeight;
  window.onscroll = function () {
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      document.querySelector('.scrollBar').style.width = (scrollTop/scrollAvail)*100   '%';
  };
}

## Related

- Previous: [electron基础构建跨平台桌面应用 web端生成EXE文件](https://www.deathghost.cn/article/javascript/42)
- Next: [JS原生的深拷贝API structuredClone()](https://www.deathghost.cn/article/javascript/120)
