能用js实现
以下是使用 JavaScript 实现的方法:
监听滚动事件
通过 window.addEventListener 监听 scroll 事件,实时获取页面滚动位置。
window.addEventListener('scroll', function() {
console.log(window.scrollY);
});
计算滚动百分比
根据文档总高度和可视窗口高度,计算当前滚动位置的百分比。

function getScrollPercentage() {
const scrollTop = window.scrollY;
const windowHeight = window.innerHeight;
const docHeight = document.documentElement.scrollHeight;
return (scrollTop / (docHeight - windowHeight)) * 100;
}
动态更新进度条
创建一个固定在页面顶部或底部的进度条元素,并随滚动百分比更新其宽度。
const progressBar = document.createElement('div');
progressBar.style.position = 'fixed';
progressBar.style.top = '0';
progressBar.style.left = '0';
progressBar.style.height = '5px';
progressBar.style.backgroundColor = 'blue';
document.body.appendChild(progressBar);
window.addEventListener('scroll', function() {
const percent = getScrollPercentage();
progressBar.style.width = percent + '%';
});
优化性能
使用 requestAnimationFrame 或节流函数避免频繁触发滚动事件导致的性能问题。

let ticking = false;
window.addEventListener('scroll', function() {
if (!ticking) {
window.requestAnimationFrame(function() {
const percent = getScrollPercentage();
progressBar.style.width = percent + '%';
ticking = false;
});
ticking = true;
}
});
兼容性处理
确保代码在旧浏览器中正常运行,可通过 document.body.scrollTop 作为回退方案。
const scrollTop = window.scrollY || document.documentElement.scrollTop || document.body.scrollTop;
自定义样式
通过 CSS 进一步美化进度条,例如添加过渡动画或圆角效果。
div[style*="position: fixed"] {
transition: width 0.1s ease;
border-radius: 0 5px 5px 0;
}






