页面进度条

在vue项目中做一个类似ECMAScript 6 入门的页面进度条

页面进度条

1.先在页面设置一个div

<div id="progress-bar"></div>

2.设置样式,使其固定在页面顶部。

#progress-bar{
  height: 5px;
  background-color: #42b983;
  position: fixed;
  top: 0;
  left: 0;
}

3.再给页面滚动添加监听器

mounted () {
    window.addEventListener('scroll', this.getBarWidth)
},
destroyed () {
    window.removeEventListener('scroll', this.getBarWidth)
},

4.获取进度条宽度

getBarWidth () {
      let barWidth = document.documentElement.scrollTop / (document.body.scrollHeight - document.body.clientHeight) * document.body.offsetWidth
      document.getElementById('progress-bar').style.width = barWidth + 'px'
}

document.body.scrollHeight网页正文全文高

document.body.clientHeight网页可见区域高

二者相减获得滚动条的长度

document.documentElement.scrollTop网页滚动条距离顶部的长度

相除获得进度的百分比

document.body.offsetWidth网页可见区域宽(包括边线的宽)

相乘则按比例获得进度条的宽度

关于获取这些长度不同浏览器规则不同,具体可以参考这篇文章→JS获取网页高度和宽度-梦深深处

5.完成

进度条

posted @ 2020-11-05 11:54  许半仙  阅读(172)  评论(0编辑  收藏  举报