请实现一个文章阅读的进度条

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reading Progress Bar</title>
    <style>
        #reading-progress {
            height: 10px;
            background-color: #e0e0e0;
            width: 100%;
            position: fixed;
            top: 0;
            left: 0;
        }

        #progress-bar {
            height: 100%;
            background-color: #4CAF50;
            width: 0%; /* Initially 0% */
        }
    </style>
</head>
<body>

    <div id="reading-progress">
        <div id="progress-bar"></div>
    </div>

    <!-- Your article content goes here -->
    <div id="article-content">
        <h1>Article Title</h1>
        <p>Lots of interesting content...</p>
        <p>More content...</p>
        <!-- ... more content ... -->
    </div>

    <script>
        window.addEventListener('scroll', function() {
            let totalHeight = document.body.scrollHeight - window.innerHeight;
            let scrolledHeight = window.pageYOffset || document.documentElement.scrollTop;
            let progressPercentage = (scrolledHeight / totalHeight) * 100;

            document.getElementById('progress-bar').style.width = progressPercentage + '%';
        });
    </script>

</body>
</html>

Explanation:

  1. HTML Structure:

    • #reading-progress: The container for the progress bar. Styled to be fixed at the top.
    • #progress-bar: The actual progress bar element, initially with 0% width.
    • #article-content: This div holds your article content.
  2. CSS Styling:

    • Basic styling for the progress bar container and the bar itself. You can customize colors and height as needed.
  3. JavaScript Logic:

    • window.addEventListener('scroll', ...): This listens for the scroll event. Every time the user scrolls, the function inside is executed.
    • totalHeight: Calculates the total scrollable height of the document.
    • scrolledHeight: Gets the current vertical scroll position.
    • progressPercentage: Calculates the percentage of the page that has been scrolled.
    • document.getElementById('progress-bar').style.width = ...: Updates the width of the progress bar based on the calculated percentage.

Key Improvements and Considerations:

  • Fixed Position: The progress bar stays at the top even when scrolling.
  • Dynamic Calculation: Accurately calculates progress even with dynamic content changes.
  • Cross-Browser Compatibility: Uses window.pageYOffset || document.documentElement.scrollTop for consistent scroll position across browsers.
  • Customization: Easily customize the appearance (color, height, etc.) with CSS.

This improved version provides a more robust and user-friendly reading progress bar. Remember to replace the placeholder content in #article-content with your actual article.

posted @ 2024-12-08 09:10  王铁柱6  阅读(10)  评论(0)    收藏  举报