根据页面长度实现阅读进度条原理

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>pageScroll</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        /*防止body的高度为100px,加1px padding实现了把body撑开*/
        body{
            padding:1px;
        }
        .test {
            width: 100px;
            height: 100px;
            background-color: #000;
            margin: 500px 0 1000px 300px;
        }
    </style>
</head>
<body>
    <div class="test"></div>
    <script>
        ;(function (w,d) {
            var domDiv = d.createElement('div');
            //修改domDiv的行内样式
            domDiv.style.cssText = 'position: fixed; top: 0; left: 0;  0; height: 7px;'+'box-shadow: 0 0 3px #999; background: -webkit-linear-gradient(left, red , blue);z-index: 999999; -webkit-transition:width .3s linear;'
            //append是jquery的方法,dom对象的是appendchild();
            d.body.appendChild(domDiv);
            //domH:可视区域的高度
            var domH = w.innerHeight||d.documentElement.clientHeight||d.body.clientHeight;
            /**
             * [通过给window添加scroll事件实现了监控的作用。]
             * @param  {[type]} ){                var divsw         [description]
             * @param  {[type]} false      [冒泡阶段]
             * @return {[type]}            [description]
             * pageYOffset:滚到了视口顶部的高度。
             * document.body.offsetHeight:body的高度
             */
            w.addEventListener('scroll',function(){
                var divsw = domDiv.style.width = Math.round(pageYOffset/(d.body.offsetHeight-domH)*100)+'%';
                /*if(parseInt(divsw,10)>50){
                    domDiv.style.backgroundColor = '#00f';
                }else{
                    domDiv.style.backgroundColor = '#f00808';
                }*/
            },false);
        })(window,document);
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/qianduanjingying/p/5072356.html