页面顶端显示滚动条进度条
需求
希望实现一个滚动条进度条,这个进度条在页面滚动时能够动态显示当前的滚动进度。
实现
可以使用 JavaScript 来动态更新进度条的宽度。以下是完整的实现代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Scroll Progress Bar</title> <style> body { margin: 0; font-family: Arial, sans-serif; } .progress-container { position: fixed; top: 0; /* bottom底部 */ left: 0; width: 100%; height: 5px; background-color: #e0e0e0; overflow: hidden; } .progress-bar { height: 100%; background-color: #4CAF50; width: 0%; transition: width 0.3s ease; /* 平滑过渡效果 */ } /* 添加一些内容以便滚动 */ .content { height: 2000px; padding-top: 20px; } </style> </head> <body> <div class="progress-container"> <div class="progress-bar"></div> </div> <div class="content"> <!-- 内容区域 --> <h1>Scroll Down to See the Progress Bar</h1> <p>Keep scrolling to see the progress bar update.</p> </div> <script> // 获取进度条元素 const progressBar = document.querySelector('.progress-bar'); // 监听滚动事件 window.addEventListener('scroll', updateProgressBar); // 初始化进度条 updateProgressBar(); function updateProgressBar() { // 计算滚动高度和总高度 const scrollHeight = document.body.scrollHeight - window.innerHeight; const scrolled = window.scrollY; const percentage = (scrolled / scrollHeight) * 100; // 更新进度条宽度 progressBar.style.width = `${percentage}%`; } </script> </body> </html> |
关键点解释:
window.addEventListener('scroll', updateProgressBar);
监听滚动事件,每次滚动时调用 updateProgressBar 数。
updateProgressBar
函数:计算滚动高度和总高度,以及当前滚动位置占总滚动高度的百分比。最终更新进度条的宽度。
transition: width 0.3s ease
为进度条宽度变化添加平滑过渡效果,使进度条变化更自然。
window.scrollY
获取当前滚动位置。
document.body.scrollHeight
获取页面总高度。
通过这两个值计算出当前滚动的百分比。
效果
进度条会随着页面滚动动态更新,显示当前滚动进度。
在页面上滑时,根据滚动位置实时更新。
可以根据需要调整进度条的颜色、高度和过渡效果。