1034 字
5 分钟
在 Astro 正文中嵌入递增数字
Astro + Svelte 行内数字递增动画完整指南
让句子中的数字动起来,并且只在数字进入视野后启动动画。组件支持可选的加号、前缀与后缀、强调样式,包括颜色、字重和字号,还支持一道与数字同步、从左向右扫过的高亮效果。
快速预览
在 MDX 中以内联方式使用组件:
这是一个例子:
1)启用 MDX
pnpm add @astrojs/mdx在 astro.config.mjs 中:
import { defineConfig } from 'astro/config';import mdx from '@astrojs/mdx';
export default defineConfig({ integrations: [mdx()],});CAUTION注意
尽量把
mdx()放在integrations的最后顺序很重要。请把 MDX 集成放在
integrations数组的末尾,让其他插件先完成转换。一些集成,例如astro-expressive-code,需要在 MDX 接管流程之前处理 Markdown/MDX,否则样式或组件可能无法正确渲染。astro.config.mjs import { defineConfig } from 'astro/config';import expressiveCode from 'astro-expressive-code';import mdx from '@astrojs/mdx';export default defineConfig({integrations: [expressiveCode(), // run first so it can transform contentmdx(), // keep MDX last],});
2)创建组件 src/components/CountUp.svelte
<script lang="ts"> import { onMount } from 'svelte';
// Core export let start = 0; export let end = 0; export let duration = 1200; // number & highlighter animation duration (ms) export let decimals = 0; export let locale: string | undefined = undefined; export let format: 'standard' | 'compact' = 'standard';
// Display export let prefix = ''; export let suffix = ''; export let plus = false;
// Accent styling export let color = '#ab8ae3'; export let weight: number | string = 700; export let scale = 1.12; // slightly larger than surrounding text
// Highlighter export let highlight = false; export let highlightColor = 'rgba(171,138,227,0.25)'; export let highlightRadius = '0.35em'; export let highlightPadY = '0.12em'; export let highlightPadX = '0.18em';
const easeOutCubic = (t: number) => 1 - Math.pow(1 - t, 3); let display = '';
function formatNumber(n: number) { const opts: Intl.NumberFormatOptions = format === 'compact' ? { notation: 'compact', maximumFractionDigits: 1 } : { minimumFractionDigits: decimals, maximumFractionDigits: decimals }; return n.toLocaleString(locale, opts); }
function run() { const t0 = performance.now(); const from = start, to = end;
const tick = (now: number) => { const p = Math.min(1, (now - t0) / duration); const v = from + (to - from) * easeOutCubic(p); display = formatNumber(p < 1 ? v : to); if (p < 1) requestAnimationFrame(tick); };
requestAnimationFrame(tick); }
onMount(run);</script>
<span class="countup" class:with-hl={highlight} style=" --dur: {duration}ms; --scale: {scale}; --color: {color}; --weight: {weight}; --hl-color: {highlightColor}; --hl-radius: {highlightRadius}; --pad-y: {highlightPadY}; --pad-x: {highlightPadX}; "> {#if highlight}<span class="hl" aria-hidden="true"></span>{/if} <span class="txt">{prefix}{display}{plus ? '+' : ''}{suffix}</span></span>
<style> .countup { position: relative; display: inline-block; line-height: 1.1; font-size: calc(1em * var(--scale)); color: var(--color); font-weight: var(--weight); vertical-align: baseline; } .countup .txt { position: relative; z-index: 1; }
.countup.with-hl .hl { position: absolute; z-index: 0; left: calc(var(--pad-x) * -1); right: calc(var(--pad-x) * -1); top: calc(var(--pad-y) * -1); bottom: calc(var(--pad-y) * -1); border-radius: var(--hl-radius); background: var(--hl-color); transform: scaleX(0); transform-origin: left center; animation: sweep var(--dur) ease-out forwards; }
@keyframes sweep { to { transform: scaleX(1); } }</style>3)在 MDX 的句子中以内联方式使用
import CountUp from "@components/CountUp.svelte";
We reached <strong style="color:#ab8ae3"> <CountUp end={370200} format="standard" plus={true} duration={5000} suffix=" plays" client:visible highlight /></strong> this month.CAUTION注意
Frontmatter 必须位于文件最顶部
只有当 frontmatter 是文件中的第一项内容时,Astro 才会解析它。
开头的---之前只要出现任何字符,包括空白、注释或 MDXimport语句,frontmatter 就会被忽略,必要的 schema 字段,例如title和published,也会显示为“缺失”。正确写法:
---title: Inline Count-Up Numbers in Astro (Svelte + MDX)published: 2025-08-26---import CountUp from "@components/CountUp.svelte";
4)在 Astro 模板中使用,不经过 MDX
---import CountUp from "@components/CountUp.svelte";---
<p class="mt-3"> Total signups <strong style="color:#ab8ae3; margin-left:.25em"> <CountUp end={272739} duration={1600} client:visible /> </strong> so far.</p>5)Props 参考
| 名称 | 类型 | 默认值 | 用途 |
|---|---|---|---|
start | number | 0 | 起始值 |
end | number | 0 | 目标值 |
duration | number (ms) | 1200 | 数字与高亮动画的持续时间 |
decimals | number | 0 | 小数位数,仅用于 format="standard" |
locale | string | undefined | undefined | 数字区域设置,例如 "en-US"、"zh-CN",默认跟随浏览器 |
format | 'standard' | 'compact' | 'standard' | 标准数字或紧凑计数格式 |
prefix | string | '' | 数字前的文本,例如 '$' |
suffix | string | '' | 数字后的文本,例如 ' plays' |
plus | boolean | false | 在末尾添加 + |
color | string | '#ab8ae3' | 文本颜色 |
weight | number | string | 700 | 字重 |
scale | number | 1.12 | 相对于周围文字的字号比例 |
highlight | boolean | false | 启用高亮扫过动画 |
highlightColor | string | rgba(171,138,227,.25) | 带透明度的高亮颜色 |
highlightRadius | string | '0.35em' | 高亮区域的圆角半径 |
highlightPadY | string | '0.12em' | 高亮区域纵向内缩留白 |
highlightPadX | string | '0.18em' | 高亮区域横向内缩留白 |
6)常用写法
带千位分隔符的标准数字
<strong style="color:#ab8ae3"> <CountUp end={272739} duration={1600} client:visible /></strong>紧凑显示
<CountUp end={350000} format="compact" plus client:visible />前缀、后缀与加号
<CountUp prefix="$" end={1999} suffix=" revenue" plus client:visible />使用小数位和区域设置
<CountUp end={12345.678} decimals={2} locale="en-US" client:visible />自定义强调样式
<CountUp end={8888} color="#ff7a00" weight={800} scale={1.2} client:visible />自定义高亮颜色与圆角
<CountUp end={1024} highlight highlightColor="rgba(255, 246, 117, .45)" highlightRadius="0.5em" client:visible/> 在 Astro 正文中嵌入递增数字
https://d-k-deng.github.io/zh-cn/posts/countup/