原生js实现滚动进度条效果

<!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 + '%';    // 计算占比
            console.log(scrollTop, scrollAvail, (scrollTop/scrollAvail)*100+"%")
            console.log(document.body.scrollHeight, document.documentElement.scrollHeight);
            console.log(document.documentElement.clientHeight, document.body.clientHeight);
        };
    }());
</script>
</html>
posted @ 2020-11-05 12:49  小默同学  阅读(581)  评论(0编辑  收藏  举报