原生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>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM