关于我
- 128篇文章
- 6年
- 1,280位读者
Odometer counter
里程表数字滚动
Roll a number toward its final value.
Also searched as: 数字从 0 滚到最终的数, 数字一位一位翻上来, 里程表那样滚动的数字, 统计数字往上涨
- Placement
- Article, Card list
- Mood
- Crisp, Technical
- Trigger
- 进入屏幕
- Site types
- 个人网站, 品牌官网, 工具和应用
How it works & accessibility
Interpolate from the starting number to the actual target value and format the result on each frame.
Best for: Article, Card list (进入屏幕).
Reduced motion: 不滚,直接是最终的数字
Mobile & touch: 和桌面一样;数字等宽,滚的时候不会把旁边的字挤来挤去
Key parameters
| Parameter | Key | Default | Range | Notes |
|---|---|---|---|---|
| 时长 | duration | 1800ms | — | — |
| 缓动 | easing | cubic-bezier(0.16, 1, 0.3, 1) | — | — |
Ready-to-paste AI prompt
Add “Odometer counter” to the article in my project: Interpolate from the starting number to the actual target value and format the result on each frame.
Parameters: duration: 1800ms, easing: cubic-bezier(0.16, 1, 0.3, 1).
Preserve existing content and layout. Respect prefers-reduced-motion by showing the final state. Content must remain visible if JavaScript fails or is disabled.
Reference: https://donglang.linter.top/effects/counter.md (canonical specification and reference code).Dependency-free reference code
CSS
/* 里程表数字滚动的样式,配合 counter.js。
数字等宽:滚的时候和滚完以后一样宽,左右不晃(.counter 写在 HTML 里,平时就是等宽数字)。
下面几条只在滚的时候用:每一位是一个小窗口,里面一个看不见的同样数字撑开大小、对齐基线;一列数字贴着窗口底边竖着排,
窗口用 clip-path 裁(不用 overflow: hidden,它会让窗口的基线跑到底边,数字比旁边的字高出一截)。
窗口就是一行的高度:数字的行高不要小于 1,不然滚的时候数字的上下边会被裁掉一点。 */
.counter {
font-variant-numeric: tabular-nums;
}
/* 一串数字(连同中间的逗号、小数点)不折行:原文的数字不会从中间断开,一个个小窗口之间却可以断,窄的地方会断成两行。单位、空格不在里面,照原文折行 */
.ct-num {
white-space: nowrap;
}
.ct-digit {
position: relative;
display: inline-block;
clip-path: inset(0);
}
.ct-ghost {
visibility: hidden;
}
.ct-strip {
position: absolute;
left: 0;
right: 0;
bottom: 0;
}
.ct-strip > span {
display: block;
text-align: center;
}
/* 滚动的那一层不让选中复制(里面一列列都是滚动过程中的数字),滚的时候复制拿到的是下面这份最终的数字 */
.ct-roll {
user-select: none;
}
/* 给读屏读的最终数字:看不见 */
.ct-sr {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}JavaScript
// 里程表数字滚动(Odometer counter)· 原生 JS,不依赖任何库。
// 改写自 StyleKit 的 counter-roll(MIT License,Copyright (c) 2026 AnxForever):每一位数字是一个小窗口,里面一列数字竖着滚到最终的那一位,
// 只动位置(不改文字),ease-out。参考了 Animation Handbook 的 Rolling Numbers(MIT License,Copyright (c) 2026 Matin Monshizadeh):
// 数字等宽(tabular-nums),滚的时候左右不晃;滚动的数字不给读屏读,读屏只读最终的数字。
// 和它们不同:最终的数字一直写在页面里(脚本没执行时也是对的),脚本只在滚的时候临时拆开,滚完换回原来的文字;
// 低位多转一两圈、高位少转,一起停下,看起来像一路数上去。
// el 里放写好的最终数字,可以带逗号、小数点、单位("1,280"、"4.9 分"、"128+"),只有 0–9 会滚。配合 counter.css。
// 返回一个清理函数:调用它会停掉动画,文字回到原样。
// 开启"减少动态"时不滚,直接是最终的数字;脚本出错或没执行时也是。ignoreReducedMotion 只给演示用。
const LOOPS = 2; // 低位最多多转几圈
export function counter(el, {
duration = 1800,
easing = 'cubic-bezier(0.16, 1, 0.3, 1)',
ignoreReducedMotion = false,
} = {}) {
if (!ignoreReducedMotion && matchMedia('(prefers-reduced-motion: reduce)').matches) return () => {};
const text = el.textContent ?? '';
const digits = [...text].filter((ch) => ch >= '0' && ch <= '9');
if (!digits.length) return () => {};
// 读屏读这一份最终的数字(滚的时候复制拿到的也是它);滚动的那份标 aria-hidden、不让选中
const sr = document.createElement('span');
sr.className = 'ct-sr';
sr.textContent = text.replace(/\s+/g, ' ').trim();
// 每一位要转几格:从 0 转到它自己,再按它左边那几位有多大多转几圈(左边是 0 就不多转,最多 LOOPS 圈)
let seen = 0;
const steps = () => {
const higher = Number(digits.slice(0, seen).join('') || 0);
const own = Number(digits[seen]);
seen += 1;
return own + 10 * Math.min(higher, LOOPS);
};
// 拆开:每段文字换成一个 aria-hidden 的 span,里面每一串数字(连同中间的逗号、小数点)放进一个不折行的 span、每一位变成小窗口,
// 别的字(单位、空格)照原样、该折行的地方还能折(原文的数字不会从中间断开,拆成小窗口以后窗口之间却可以断)。
// 记下原来的文字节点,滚完换回去
const nodes = [];
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
for (let n = walker.nextNode(); n; n = walker.nextNode()) nodes.push(n);
const swaps = [];
const strips = [];
nodes.forEach((node) => {
if (!node.data) return;
const box = document.createElement('span');
box.className = 'ct-roll';
box.setAttribute('aria-hidden', 'true');
node.data.split(/(\d(?:[\d.,]*\d)?)/).forEach((part, i) => {
if (!part) return;
if (i % 2 === 0) { box.append(part); return; }
const run = document.createElement('span');
run.className = 'ct-num';
box.append(run);
[...part].forEach((ch) => {
if (ch < '0' || ch > '9') { run.append(ch); return; }
// 小窗口:里面一个看不见的同样数字撑开大小、对齐基线;一列数字贴着窗口底边,平时露出的是最后一个(就是最终的那一位)
const n = steps();
const win = document.createElement('span');
win.className = 'ct-digit';
const ghost = document.createElement('span');
ghost.className = 'ct-ghost';
ghost.textContent = ch;
const strip = document.createElement('span');
strip.className = 'ct-strip';
for (let k = 0; k <= n; k += 1) {
const d = document.createElement('span');
d.textContent = String(k % 10);
strip.append(d);
}
win.append(ghost, strip);
run.append(win);
strips.push([strip, n]);
});
});
node.replaceWith(box);
swaps.push([node, box]);
});
el.prepend(sr);
const anims = [];
let done = false;
const restore = () => {
if (done) return;
done = true;
anims.forEach((a) => a.cancel());
// 这段文字已经被别的脚本换掉了:不动它
if (sr.parentNode !== el) return;
swaps.forEach(([node, box]) => box.replaceWith(node));
sr.remove();
};
try {
// 每一列从露出第一个(0)开始往上滚,回到原位露出最后一个;一起开始、一起停下
strips.forEach(([strip, n]) => {
anims.push(strip.animate([{ translate: `0 ${(100 * n) / (n + 1)}%` }, { translate: '0 0' }], { duration, easing, fill: 'backwards' }));
});
} catch (err) {
// 动画起不来(比如脚本出错):换回原来的文字
restore();
throw err;
}
Promise.all(anims.map((a) => a.finished)).then(restore, restore);
return restore;
}
// 一个或一组数字:各自快进入屏幕时开始滚(只滚一次)。
// 离屏幕底边还有 40px 时就开始:滚的第一帧是 0,等露出一截再开始,会先看到最终的数字、再跳回 0 滚上去。
// 调用时已经在屏幕里的马上开始(等观察器报告要晚一帧,那一帧最终的数字已经露过了)。已经滚过去的、往回滚从上边进来的不滚。
// root 是滚动的那个框,默认整个页面(document 让提前量按元素所在页面自己的视口算,放在 iframe 里也管用)。
/**
* @param {Element | Iterable<Element>} els
* @param {{ root?: Document | Element, duration?: number, easing?: string, ignoreReducedMotion?: boolean }} [options]
*/
export function counterOnEnter(els, { root = document, ...options } = {}) {
const list = els instanceof Element ? [els] : [...els];
const io = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (!entry.isIntersecting) return;
io.unobserve(entry.target);
if (entry.boundingClientRect.top >= (entry.rootBounds?.top ?? 0)) counter(entry.target, options);
});
}, { root, threshold: 0, rootMargin: '0px 0px 40px 0px' });
const view = root === document ? { top: 0, bottom: innerHeight } : root.getBoundingClientRect();
list.forEach((el) => {
const r = el.getBoundingClientRect();
if (r.bottom <= view.top) return;
if (r.top < view.bottom) counter(el, options);
else io.observe(el);
});
return () => io.disconnect();
}HTML
<!-- 里程表数字滚动:最终的数字直接写在页面里(加上 class="counter"),进入屏幕时从 0 滚上来;单位写在数字外面 -->
<ul class="stats">
<li><b class="counter">128</b> 篇文章</li>
<li><b class="counter">6</b> 年</li>
<li><b class="counter">1,280</b> 位读者</li>
</ul>
<script type="module">
import { counterOnEnter } from './counter.js';
counterOnEnter(document.querySelectorAll('.counter'));
</script>