页面顶部挂一根彩色进度条,往下读它跟着涨,读到底正好满格。长文、教程类站点装上很直观——读者随时知道还剩多少。十几行代码,不用插件。下面每块都能点「预览效果」直接看,滚动一下就能看到效果。
原版 · jQuery 版
$(window).scroll(function() {
var a = $(window).scrollTop(),
c = $(document).height(),
b = $(window).height();
scrollPercent = a / (c - b) * 100;
scrollPercent = scrollPercent.toFixed(1);
$("#percentageCounter").css({
width: scrollPercent + "%"
});
}).trigger("scroll");配上这个 HTML 结构使用:
```html
<div id="percentageCounter"></div>
```
逻辑是对的,但这段代码单独粘进去是看不到效果的——它只改了 width,而 #percentageCounter 没有任何 CSS,一个没有高度、没有背景色的 div 宽度再变也看不见。这是最容易被忽略的一点,下面补上。
另外几处问题,我逐个验证过:
① 页面不足一屏时会算出 NaN
c - b 是「文档总高 − 视口高」,也就是可滚动的距离。当文章内容不够长、页面根本没有滚动条时,c - b 等于 0,于是 a / 0:
- 分子也是 0 →
0 / 0= NaN - 结果
width: NaN%是无效值,浏览器直接忽略
实测过:短页面上进度条会完全不动,且控制台没有任何报错(NaN 不抛异常),很难排查。
② scrollPercent 没有声明,成了隐式全局变量
少了 var / let / const。在严格模式下('use strict'、ES Module、打包后的代码里很常见)会直接抛 ReferenceError: scrollPercent is not defined,整个脚本挂掉。
③ scroll 事件触发极密,每次都读写 DOM
滚动时 scroll 事件每秒能触发几十次,每次都做 $(window).height()(强制浏览器重排)再写 width,在低端手机上会掉帧。应该缓存尺寸 + 用 requestAnimationFrame 合并。
④ 依赖 jQuery
现在多数主题不再默认加载 jQuery,或者版本冲突。这段其实不需要 jQuery。
修复版 · 原生 JS,不依赖 jQuery
<style>
/* 顶部阅读进度条 · 修复版 */
#wxz-progress{
position:fixed;top:0;left:0;height:3px;width:0;
background:linear-gradient(90deg,#5b7cfa,#9f7aea,#f56565);
z-index:99999;pointer-events:none;
/* 只在 width 变化时过渡,避免拖动滚动条时"追赶"的迟滞感 */
transition:width .1s linear;
border-radius:0 2px 2px 0}
@media (prefers-reduced-motion:reduce){
#wxz-progress{transition:none}
}
/* 演示用:把页面撑高,好看到滚动效果 */
.demo-body{height:1800px;padding:20px;background:#fff;font:14px/1.8 sans-serif;color:#4a5568}
.demo-body h3{margin:0 0 10px;font-size:16px;color:#2d3748}
</style>
<div id="wxz-progress"></div>
<div class="demo-body">
<h3>向下滚动,看页面顶部的进度条 →</h3>
<p>这是一个撑高的演示容器。真实使用时删掉 .demo-body 这段样式即可,进度条会跟着你文章的实际高度走。</p>
<p><a href="https://wxzcw.com/">维形筑网</a> · 让每一个网站闪闪发光 ✨</p>
</div>
<script>
(function () {
'use strict';
var bar = document.getElementById('wxz-progress');
if (!bar) { return; }
var docHeight = 0, winHeight = 0, ticking = false;
function measure() {
docHeight = document.documentElement.scrollHeight;
winHeight = window.innerHeight;
}
function update() {
ticking = false;
var scrollable = docHeight - winHeight;
// 关键:除零保护。页面不足一屏时直接归零,避免算出 NaN
var percent = scrollable > 0
? (window.scrollY / scrollable) * 100
: 0;
// 夹在 0~100,防止某些浏览器的弹性滚动算出负值或超过 100
if (percent < 0) { percent = 0; }
if (percent > 100) { percent = 100; }
bar.style.width = percent.toFixed(2) + '%';
}
function onScroll() {
if (!ticking) {
ticking = true;
window.requestAnimationFrame(update);
}
}
window.addEventListener('scroll', onScroll, { passive: true });
window.addEventListener('resize', function () { measure(); update(); });
measure();
update();
})();
</script>改了这些,每条都实测过:
- 除零保护:
scrollable > 0才计算,否则归零。短页面不再出 NaN。 - 严格模式安全:所有变量都声明了,外层包了 IIFE,不污染全局。
- rAF 节流:
requestAnimationFrame把一帧内的多次 scroll 合并成一次更新;{ passive: true }告诉浏览器不会调preventDefault,滚动更顺。 - 夹取 0~100:iOS 的弹性滚动会让
scrollY出现负值或超出,不夹的话进度条会反向或溢出。 - 尺寸缓存:
docHeight/winHeight只在 resize 时重新测量,不在每次滚动里读(读scrollHeight会触发重排)。 - 不依赖 jQuery。
渐变流光版 · 条子会流动
进度条本身加一层流动的光效,颜色随滚动位置变化。
<style>
#wxz-progress2{
position:fixed;top:0;left:0;height:4px;width:0;
z-index:99999;pointer-events:none;border-radius:0 3px 3px 0;
background:linear-gradient(90deg,#00c6ff,#0072ff,#7f00ff,#e100ff);
background-size:300% 100%;
animation:wxz-flow 3s linear infinite;
box-shadow:0 0 8px rgba(0,114,255,.6);
transition:width .1s linear}
@keyframes wxz-flow{
from{background-position:0% 50%}
to{background-position:100% 50%}
}
@media (prefers-reduced-motion:reduce){
#wxz-progress2{animation:none;transition:none}
}
.demo-body2{height:1800px;padding:20px;background:#fff;font:14px/1.8 sans-serif;color:#4a5568}
.demo-body2 h3{margin:0 0 10px;font-size:16px;color:#2d3748}
</style>
<div id="wxz-progress2"></div>
<div class="demo-body2">
<h3>向下滚动,条子本身也在流动 →</h3>
<p>background-size 设成 300% 再把 background-position 动画起来,渐变就会横向流动。</p>
<p>维形筑网 · 让每一个网站闪闪发光 ✨</p>
</div>
<script>
(function () {
'use strict';
var bar = document.getElementById('wxz-progress2');
if (!bar) { return; }
var docH = 0, winH = 0, ticking = false;
function measure() {
docH = document.documentElement.scrollHeight;
winH = window.innerHeight;
}
function update() {
ticking = false;
var s = docH - winH;
var p = s > 0 ? (window.scrollY / s) * 100 : 0;
bar.style.width = Math.min(100, Math.max(0, p)).toFixed(2) + '%';
}
window.addEventListener('scroll', function () {
if (!ticking) { ticking = true; window.requestAnimationFrame(update); }
}, { passive: true });
window.addEventListener('resize', function () { measure(); update(); });
measure(); update();
})();
</script>流光的原理是 background-size:300% 100% 让渐变比容器宽三倍,再用 @keyframes 动画 background-position,渐变就横向流动起来。box-shadow 加了一层光晕,深色站点上更明显。
带百分比数字版
右上角多一个圆形进度环,显示具体数字。比纯条子信息更明确。
<style>
#wxz-progress3{
position:fixed;top:0;left:0;height:3px;width:0;
background:linear-gradient(90deg,#5b7cfa,#9f7aea);
z-index:99999;pointer-events:none;transition:width .1s linear}
#wxz-pct{
position:fixed;right:16px;bottom:16px;width:46px;height:46px;border-radius:50%;
background:conic-gradient(#5b7cfa 0%, #e2e8f0 0%);
display:flex;align-items:center;justify-content:center;
z-index:99998;font:600 12px/1 sans-serif;color:#2d3748;
box-shadow:0 2px 10px rgba(0,0,0,.12)}
#wxz-pct span{
width:36px;height:36px;border-radius:50%;background:#fff;
display:flex;align-items:center;justify-content:center}
.demo-body3{height:1800px;padding:20px;background:#fff;font:14px/1.8 sans-serif;color:#4a5568}
.demo-body3 h3{margin:0 0 10px;font-size:16px;color:#2d3748}
</style>
<div id="wxz-progress3"></div>
<div id="wxz-pct"><span>0%</span></div>
<div class="demo-body3">
<h3>向下滚动,看右下角的百分比环 →</h3>
<p>conic-gradient 画环,中心盖一个白色小圆就成了环形进度。</p>
<p>维形筑网 · 让每一个网站闪闪发光 ✨</p>
</div>
<script>
(function () {
'use strict';
var bar = document.getElementById('wxz-progress3');
var pct = document.getElementById('wxz-pct');
var num = pct ? pct.querySelector('span') : null;
if (!bar) { return; }
var docH = 0, winH = 0, ticking = false, last = -1;
function measure() {
docH = document.documentElement.scrollHeight;
winH = window.innerHeight;
}
function update() {
ticking = false;
var s = docH - winH;
var p = s > 0 ? (window.scrollY / s) * 100 : 0;
p = Math.min(100, Math.max(0, p));
bar.style.width = p.toFixed(2) + '%';
var r = Math.round(p);
// 只有整数变化时才更新,避免每帧都改 DOM 文本
if (num && r !== last) {
last = r;
num.textContent = r + '%';
pct.style.background = 'conic-gradient(#5b7cfa ' + r + '%, #e2e8f0 ' + r + '%)';
}
}
window.addEventListener('scroll', function () {
if (!ticking) { ticking = true; window.requestAnimationFrame(update); }
}, { passive: true });
window.addEventListener('resize', function () { measure(); update(); });
measure(); update();
})();
</script>环是用 conic-gradient 画的,中心再盖一个白色小圆就成了环形。这里多做了一处优化:只在整数百分比变化时才更新文字,否则每帧都改 DOM 文本,白白开销。
改的时候注意这几点
- 一定要给容器加 CSS:原版最大的坑就在这——只有
width变化,没有height和background的话什么都看不见。最少需要position:fixed+height+background三行。 z-index要给够:99999这类大值,避免被主题的头部导航盖住。如果你的主题头部 z-index 更高,再往上加。pointer-events:none别忘了:进度条浮在最顶层,不加这行会挡住顶部区域的点击(比如导航菜单)。- 页面不足一屏要保护:
scrollHeight - innerHeight可能是 0,除零会出 NaN,且控制台不报错,很难查。 - 用
passive: true:告诉浏览器不会阻止默认滚动,滚动性能更好。 - 想改粗细和颜色:改
height和background即可。height:2px更精致,5px更醒目。 - 去掉过渡动画:删掉
transition:width,条子会严格跟随滚动位置(更精确但略生硬)。 - **演示用的
.demo-*样式记得删**:那几段是为了在预览里撑出滚动区域的,你自己的文章本来就有高度。
怎么用
WordPress:代码块整段粘进「自定义 HTML」区块即可(原生 JS 版不需要 jQuery)。想全站生效、每篇文章都有,就把 <div id="wxz-progress"> 放进主题的 header.php,JS 放进 footer.php 或「额外 CSS」下方的自定义 JS 区。
Typecho:HTML 放 header.php,JS 放 footer.php。
只有 JS 部分需要动主题的话,推荐用子主题,避免主题更新后丢失。
兼容性
requestAnimationFrame、scrollHeight、passive 事件选项在 Chrome / Edge / Firefox / Safari 全系支持;conic-gradient 需要 Chrome 69+ / Safari 12.1+,更老的浏览器上百分比环不出色(但条子正常)。微信内置浏览器无问题。
代码仅供学习交流,禁止商用。更多网站美化代码,前往 维形筑网 www.wxzcw.com。
作者:Flechazo
如若转载,请注明出处:维形筑网 https://wxzcw.com