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