# 靠近变粗 Text Proximity > 标题的每个字按离鼠标的远近变粗变细,最近的最粗。 分类:鼠标特效 · 角色:点缀(贴在某个元素上,一页两三个) [全部组件和流程](https://www.dachuiai.com/llms.txt) · [鼠标特效选型规则](https://www.dachuiai.com/guides/cursor.md) ## 给 AI:用户把这个组件发给了你 1. 先看用户的项目:框架、页面类型、现在的风格、手机还是电脑为主。 2. 对照下面的「适合 / 不适合」判断合不合适。不合适就直接说,并从[鼠标特效选型规则](https://www.dachuiai.com/guides/cursor.md)或[全部组件](https://www.dachuiai.com/llms.txt)里另挑一个。 3. 合适就按「装进项目」装好,示例里的文字和图片换成用户自己的。 4. 告诉用户用了什么、放在哪个文件、以后想改快慢、颜色、大小改哪个参数。 ## 什么时候用 - 适合:字体网站、设计工作室、品牌官网的大标题,字少(2 到 12 个字)、字号大。 - 不适合:正文和小字(字重一变会挤动排版);没有可变字体(普通字体只会一档一档地跳);一页好几个标题都加。 - 适合的网站:作品集、官网、活动页 - 放在:标题、首屏 - 手机上:没效果:手机上停在最细的样子,所以 min 的字重要能当正常标题用。 - 性能代价:低:只改字重,没在动就停。 - 常搭配:[滚动出现 Scroll Reveal](https://www.dachuiai.com/c/scroll-reveal.md)、[跑马灯 Marquee](https://www.dachuiai.com/c/marquee.md) ## 装进项目 - 写法:React 18 以上 + TypeScript + Tailwind CSS v4,一个文件就能用,不引用别的组件。 - 依赖:只用 react,不用另外安装 - 文件:原样存成 `text-proximity.tsx`(比如 `src/components/text-proximity.tsx`)。能跑命令就下载[原文](https://www.dachuiai.com/code/text-proximity.tsx),比手抄准:`curl -fsSL -o src/components/text-proximity.tsx https://www.dachuiai.com/code/text-proximity.tsx`(Windows 写 `curl.exe`)。下载完看一眼第一行是 `import`,不是网页。 - 导出:`TextProximity` 是可以直接用的部分;最后的 `export default` 是演示示例,只作参考。 - 字体:示例用了本站的 [/fonts/proximity-sans-sc.woff2](https://www.dachuiai.com/fonts/proximity-sans-sc.woff2)、[/fonts/proximity-grotesk.woff2](https://www.dachuiai.com/fonts/proximity-grotesk.woff2)(只含示例里那几个字的子集,许可见 [/fonts/OFL.txt](https://www.dachuiai.com/fonts/OFL.txt))。换成用户自己的字体;只想先看效果,可以从本站同样的路径下载,放进项目的 public 目录。 - 注意:必须是可变字体(带 wght 轴)。中文可变字体很大,正式用时按标题里的字取子集(示例的子集只有 6KB)。字重变了字宽也会变一点,字少的大标题看不出来。 - 保留代码里 `prefers-reduced-motion` 的处理:用户开了「减弱动态效果」时内容照样完整显示。 - Next.js(有 app 文件夹):文件第一行加 `'use client';`。 - 用 JavaScript 不用 TypeScript:Vite 和 Next.js 都能直接用 .tsx 文件;也可以删掉类型标注,改名 .jsx。 - 没有 Tailwind:先装 Tailwind CSS v4(Vite 项目 `npm i tailwindcss @tailwindcss/vite`,vite 配置的 plugins 里加 `tailwindcss()`,入口引入的那个 CSS 文件(一般是 `src/index.css`)第一行写 `@import "tailwindcss";`),或者把类名改写成项目用的样式。 - 已经装了 Tailwind v3:别为了一个组件升级。类名大多通用,少数 v4 写法要换,比如焦点框 `outline-2` 在 v3 里要写成 `outline outline-2`。 - 不是 React(Vue、Svelte、小程序、纯 HTML):照着代码的做法改写,时长、曲线、参数保持一样。Wix、有赞这类建站平台装不进代码,告诉用户去平台自带的动效设置里找。 ## 参数 | 参数 | 默认值 | 作用 | | --- | --- | --- | | `text` | | 要显示的字,用 \n 换行 | | `min` | `300` | 远处的字重 | | `max` | `900` | 离鼠标最近的字重 | | `range` | `200` | 鼠标多远以内的字会变粗(px) | | `className` | `''` | 加在最外层的类名,用来调大小、位置、间距 | | `style` | | 行内样式,一般拿来设字体(font-family) | | `onPeak` | | 每一帧告诉你现在最粗的那个字是多少,可以拿来做刻度(不需要就不传) | ## 你可以说 > 标题用可变字体:按每个字到鼠标的距离调字重,最近的 900,远处 300,变化要平滑。 ## 完整代码 ```tsx import {useEffect, useRef, type CSSProperties} from 'react'; /* --------------------------------------------------------------- * TextProximity 靠近变粗 * 标题用可变字体:按每个字到鼠标的距离调字重,离得最近的最粗,远处最细,中间平滑过渡,时间上也平滑跟上。 * 字体必须是可变字体(带 wght 轴,比如思源黑体、Space Grotesk 的可变版本),普通字体只会一档一档地跳。 * 用 className 或 style 给它设字体;字体里要有 min 到 max 之间的字重。 * 读屏读到的是完整的一句话,不会一个字一个字地读。 * 只在有鼠标的设备上变;手机、平板上停在最细的样子。没在动的时候就停下,不占动画。 * text:要显示的字,用 \n 换行 * min:远处的字重 * max:离鼠标最近的字重 * range:鼠标多远以内的字会变粗(px) * style:行内样式,一般拿来设字体(font-family) * onPeak:每一帧告诉你现在最粗的那个字是多少,可以拿来做刻度(不需要就不传) * ------------------------------------------------------------- */ type Props = {text: string; min?: number; max?: number; range?: number; className?: string; style?: CSSProperties; onPeak?: (weight: number) => void}; export function TextProximity({text, min = 300, max = 900, range = 200, className = '', style, onPeak}: Props) { const root = useRef(null); const peak = useRef(onPeak); peak.current = onPeak; useEffect(() => { if (!matchMedia('(pointer: fine)').matches) return; const el = root.current!; const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches; const chars = [...el.querySelectorAll('[data-ch]')].map((s) => ({s, x: 0, y: 0, w: min})); const m = {x: 0, y: 0, near: false}; let raf = 0, prev = 0; // 量每个字的中心(相对这一段字),字重变了会稍微挤开一点,不影响手感 const measure = () => { const box = el.getBoundingClientRect(); for (const c of chars) { const r = c.s.getBoundingClientRect(); c.x = r.left - box.left + r.width / 2; c.y = r.top - box.top + r.height / 2; } }; const frame = (now: number) => { const dt = Math.min(0.05, Math.max(0, now - prev) / 1000); prev = now; let top = min, moving = false; for (const c of chars) { const d = m.near ? Math.hypot(m.x - c.x, m.y - c.y) : Infinity; const t = Math.max(0, 1 - d / range), e = t * t * (3 - 2 * t); const to = min + (max - min) * e; c.w = reduce ? to : c.w + (to - c.w) * (1 - Math.exp(-11 * dt)); if (Math.abs(c.w - to) > 0.5) moving = true; c.s.style.fontVariationSettings = `"wght" ${c.w.toFixed(1)}`; if (c.w > top) top = c.w; } peak.current?.(top); raf = moving || m.near ? requestAnimationFrame(frame) : 0; }; const kick = () => { if (!raf) { prev = performance.now(); raf = requestAnimationFrame(frame); } }; // 鼠标在这段字外面也算:离得够近就开始变 const move = (e: PointerEvent) => { if (e.pointerType === 'touch') return; const r = el.getBoundingClientRect(); m.x = e.clientX - r.left; m.y = e.clientY - r.top; const near = m.x > -range && m.y > -range && m.x < r.width + range && m.y < r.height + range; if (near || m.near) { m.near = near; kick(); } }; const leave = () => { m.near = false; kick(); }; measure(); document.fonts?.ready.then(measure); const ro = new ResizeObserver(measure); ro.observe(el); addEventListener('pointermove', move, {passive: true}); document.documentElement.addEventListener('pointerleave', leave); return () => { cancelAnimationFrame(raf); ro.disconnect(); removeEventListener('pointermove', move); document.documentElement.removeEventListener('pointerleave', leave); }; }, [text, min, max, range]); return ( {text.replace(/\n/g, '')} {text.split('\n').map((line, i) => ( {[...line].map((ch, j) => ( {ch} ))} ))} ); } /* ---------------- 示例:字体网站的标题屏 ---------------- */ // 演示用的两个可变字体只取了这几个字的子集(本站 /fonts/ 下,许可见 /fonts/OFL.txt);换成你自己的可变字体即可 const FONTS = ` @font-face{font-family:"Proximity Sans SC";src:url(/fonts/proximity-sans-sc.woff2) format("woff2");font-weight:100 900;font-display:block} @font-face{font-family:"Proximity Grotesk";src:url(/fonts/proximity-grotesk.woff2) format("woff2");font-weight:300 700;font-display:block}`; const MONO = '"JetBrains Mono", "SF Mono", ui-monospace, Menlo, monospace'; const GRAIN = `url("data:image/svg+xml;utf8,")`; const TICKS = [300, 400, 500, 600, 700, 800, 900]; export default function TextProximityDemo() { const mark = useRef(null); const near = useRef(null); const show = (w: number) => { if (!mark.current || !near.current) return; mark.current.style.transform = `translateX(${(((w - 300) / 600) * 100).toFixed(2)}cqw)`; near.current.textContent = String(Math.round(w / 10) * 10); }; return (
可变字体 Variable wght 300 — 900
{TICKS.map((w, i) => ( {w} ))}
最近的字 300 Noto Sans SC
); } ```