页面的阅读进度条的css实现方案

本文转载自 https://juejin.cn/post/7033668584026931214 ,如有侵权,告知删之.
实现方案之js,
原理: 页面中有父子盒子,父盒子固定定位, 子盒子绝对定位, 父子盒子背景色设置不一样,,让子盒子覆盖在父盒子上,通过计算子盒子的长度,来动态改变颜色的长度变化, 具体代码如下:

HTML部分
    <div class="read_pro_inner"></div>
</div> ```
#####css部分
``` .read_pro {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 3px;
    background-color: #DDD;
}
.read_pro_inner {
    content: '';
    position: absolute;
    left: 0;
    height: 100%;
    background-color: #0089f2;
} ```
##### js计算部分
``` /*
 大家可能会有疑惑,为什么分母是 scrollHeight- clientHeight 而不是 scrollHeight?
当滚动条滚动到底部时,浏览器此时仍显示一屏内容,此时滚动条无法再滚动,scrollTop 无法再增加,因此 scrollTop 的最大值是 scrollHeight- clientHeight ,如果使用 scrollHeight 做分母,阅读进度最终无法达到 100%
*/
readProInner.style.width = +(scrollTop / (scrollHeight- clientHeight)).toFixed(2)*100 + '%' ```

``` /*使用 js 实现需要监听 scroll 事件,而且滚动时有可能是频繁的 scroll 事件触发,有可能会造成一定的性能浪费,所以我们来一起学习 css 实现方案*/
document.addEventListener('scroll', function(e) {
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    readProInner.style.width = +(scrollTop/(scrollHeight-clientHeight)).toFixed(2)*100 + '%'
}) ```

## css实现方式(比较简单,且不消耗性能)
#####代码如下,亲测好用.

 ``` body{  
    background: linear-gradient(to right top, #0089f2 50%, #DDD 50%);
    /* 通过 calc 函数配合 100vh 就可以从总长中删除一屏的高度 */
    /* 100vh 浏览器视口的高度 */
    background-size: 100% calc(100% - 100vh + 4px);
    background-repeat: no-repeat;
}
body:before{
    content:'';
    /* fixed定位 */
    position: fixed;
    /* 同时设置 top 和 bottom 可以拉伸 height */
    /* 设置高度为 100% - 3px */
    top: 3px;
    bottom: 0;
    width: 100%;
    /* 降低层级,白块显示在文字之下 */
    z-index: -1;
    background: white;
} ```
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容