# 带字光标 Cursor Label > 平时是小圆点,移到图片上变成写着"查看"的圆,移到轮播上变成"拖动"。 分类:鼠标特效 · 角色:点缀(贴在某个元素上,一页两三个) [全部组件和流程](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. 告诉用户用了什么、放在哪个文件、以后想改快慢、颜色、大小改哪个参数。 ## 什么时候用 - 适合:作品集、设计公司、品牌官网的项目列表和可拖动的轮播,告诉人这里能点开、能拖。 - 不适合:按钮上已经写清楚的地方;电商列表(要看价格,不要看光标);后台;同一页已经有别的自定义光标。 - 适合的网站:作品集、官网、活动页 - 放在:全站、列表、卡片 - 手机上:没效果:手机上什么都不加,轮播照样能用手指拖。 - 性能代价:低:一个圆,只改 transform。 - 常搭配:[3D 轮播 3D Carousel](https://www.dachuiai.com/c/carousel-3d.md)、[无限画廊 Infinite Gallery](https://www.dachuiai.com/c/infinite-gallery.md) ## 装进项目 - 写法:React 18 以上 + TypeScript + Tailwind CSS v4,一个文件就能用,不引用别的组件。 - 依赖:只用 react,不用另外安装 - 文件:原样存成 `cursor-label.tsx`(比如 `src/components/cursor-label.tsx`)。能跑命令就下载[原文](https://www.dachuiai.com/code/cursor-label.tsx),比手抄准:`curl -fsSL -o src/components/cursor-label.tsx https://www.dachuiai.com/code/cursor-label.tsx`(Windows 写 `curl.exe`)。下载完看一眼第一行是 `import`,不是网页。 - 导出:`CursorLabel` 是可以直接用的部分;最后的 `export default` 是演示示例,只作参考。 - 注意:给元素加 data-cursor-label="查看",data-cursor-color 换这一处圆的颜色。示例里能拖的轮播(Rail)是示例自己的,要用就一起拷走。 - 保留代码里 `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、有赞这类建站平台装不进代码,告诉用户去平台自带的动效设置里找。 ## 参数 | 参数 | 默认值 | 作用 | | --- | --- | --- | | `children` | | 包在里面的内容 | | `size` | `96` | 写字时圆的直径(px) | | `dot` | `14` | 平时小圆点的直径(px) | | `color` | `'#F2F0EA'` | 圆的颜色 | | `ink` | `'#0E0F12'` | 字的颜色 | | `className` | `''` | 加在最外层的类名,用来调大小、位置、间距 | ## 你可以说 > 光标移到图片上变成写着“查看”的圆,移到轮播上变成“拖动”,其他地方是小圆点,切换带缩放过渡。 ## 完整代码 ```tsx import {useEffect, useRef, useState, type KeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode} from 'react'; /* --------------------------------------------------------------- * CursorLabel 带字光标 * 平时是一个小圆点;移到能打开或能拖动的东西上,长成一个写着字的圆("查看""拖动"),切换带缩放弹簧。 * 给元素加 data-cursor-label="查看" 就行;data-cursor-color 可以换这一处圆的颜色。 * 只在这块区域里替换光标;手机、平板上什么都不加。开了「减弱动态效果」直接切换、不弹。 * size:写字时圆的直径(px) * dot:平时小圆点的直径(px) * color:圆的颜色 * ink:字的颜色 * ------------------------------------------------------------- */ type Props = {children: ReactNode; size?: number; dot?: number; color?: string; ink?: string; className?: string}; export function CursorLabel({children, size = 96, dot = 14, color = '#F2F0EA', ink = '#0E0F12', className = ''}: Props) { const root = useRef(null); const disc = useRef(null); const text = useRef(null); const [on, setOn] = useState(false); const [label, setLabel] = useState({text: '', bg: color}); useEffect(() => { if (!matchMedia('(pointer: fine)').matches) return; setOn(true); const el = root.current!, d = disc.current!; const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches; const small = dot / size; const m = {x: 0, y: 0, in: false, down: false, hot: false}; const c = {x: 0, y: 0, shown: 0, s: small, v: 0}; let raf = 0, prev = 0, fresh = true, current: Element | null = null; const frame = (now: number) => { const dt = Math.min(0.05, Math.max(0, now - prev) / 1000); prev = now; const target = m.hot ? (m.down ? 0.84 : 1) : small; if (reduce) Object.assign(c, {x: m.x, y: m.y, s: target, v: 0, shown: m.in ? 1 : 0}); else { const k = (rate: number) => 1 - Math.exp(-rate * dt); c.x += (m.x - c.x) * k(30); c.y += (m.y - c.y) * k(30); c.shown += ((m.in ? 1 : 0) - c.shown) * k(14); for (let i = 0, n = Math.ceil(dt / 0.004), h = dt / n; i < n; i++) { c.v += (-230 * (c.s - target) - 19 * c.v) * h; c.s += c.v * h; } } const s = Math.max(0.02, c.s), grown = Math.min(1, Math.max(0, (s - small) / (1 - small))); d.style.opacity = c.shown.toFixed(3); d.style.transform = `translate(${c.x - size / 2}px, ${c.y - size / 2}px) scale(${s.toFixed(4)})`; if (text.current) text.current.style.opacity = (m.hot ? grown : grown * grown).toFixed(3); const still = Math.abs(c.x - m.x) + Math.abs(c.y - m.y) < 0.1 && Math.abs(c.s - target) < 0.001 && Math.abs(c.v) < 0.01 && Math.abs(c.shown - (m.in ? 1 : 0)) < 0.002; raf = still ? 0 : requestAnimationFrame(frame); }; const kick = () => { if (!raf) { prev = performance.now(); raf = requestAnimationFrame(frame); } }; const pick = (t: EventTarget | null) => { // 拖动时手指按住不放,字不换 if (m.down && current) return; const hit = (t as Element | null)?.closest?.('[data-cursor-label]') ?? null; if (hit === current) return; current = hit; m.hot = !!hit; // 离开时保留上一个字,圆缩小的同时淡掉 if (hit instanceof HTMLElement) setLabel({text: hit.dataset.cursorLabel ?? '', bg: hit.dataset.cursorColor ?? color}); }; const move = (e: PointerEvent) => { if (e.pointerType === 'touch') return; const r = el.getBoundingClientRect(); Object.assign(m, {x: e.clientX - r.left, y: e.clientY - r.top, in: true}); if (fresh) { fresh = false; c.x = m.x; c.y = m.y; } pick(e.target); kick(); }; const leave = () => { m.in = false; fresh = true; if (!m.down) pick(null); kick(); }; const down = (e: PointerEvent) => { if (e.pointerType !== 'touch') { m.down = true; kick(); } }; const up = (e: PointerEvent) => { m.down = false; pick(m.in ? document.elementFromPoint(e.clientX, e.clientY) : null); kick(); }; el.addEventListener('pointermove', move); el.addEventListener('pointerleave', leave); el.addEventListener('pointerdown', down); addEventListener('pointerup', up); return () => { cancelAnimationFrame(raf); el.removeEventListener('pointermove', move); el.removeEventListener('pointerleave', leave); el.removeEventListener('pointerdown', down); removeEventListener('pointerup', up); }; }, [size, dot, color]); return (
{children}
{label.text}
); } /* ---------------- 示例:设计公司的项目页 ---------------- */ const GROTESK = '"Space Grotesk", "SF Pro Display", ui-sans-serif, system-ui, sans-serif'; const COVERS = [ {no: '01', name: '浅滩', kind: '品牌影像', img: 'beach-waves'}, {no: '02', name: '云上', kind: '航空官网', img: 'cloud-sea'}, ]; const MORE = ['rainy-glass', 'iridescent-silk', 'milky-way', 'ink-wash', 'waves-3d', 'black-hole', 'nebula']; const ITEM = 208, GAP = 14; // 一排真能拖的轮播:松手后带一点惯性,拖过头会弹回来;键盘左右键一次走一张 function Rail() { const rail = useRef(null); const track = useRef(null); const st = useRef({pos: 0, vel: 0, goal: null as number | null, drag: null as {x: number; pos: number; t: number} | null, raf: 0, prev: 0}); const bounds = () => Math.min(0, rail.current!.clientWidth - 64 - track.current!.scrollWidth); const paint = () => { track.current!.style.transform = `translateX(${st.current.pos.toFixed(2)}px)`; }; const run = () => { const s = st.current; if (s.raf) return; const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches; s.prev = performance.now(); const frame = (now: number) => { if (!rail.current || !track.current) { s.raf = 0; return; } // 已经卸载 const dt = Math.min(0.05, Math.max(0, now - s.prev) / 1000); s.prev = now; const lo = bounds(); if (s.goal != null) { s.pos = reduce ? s.goal : s.pos + (s.goal - s.pos) * (1 - Math.exp(-12 * dt)); if (Math.abs(s.goal - s.pos) < 0.3) { s.pos = s.goal; s.goal = null; } } else if (!s.drag) { s.pos += reduce ? 0 : s.vel * dt; s.vel *= Math.exp(-4.2 * dt); if (s.pos > 0) s.pos += (0 - s.pos) * (1 - Math.exp(-12 * dt)); if (s.pos < lo) s.pos += (lo - s.pos) * (1 - Math.exp(-12 * dt)); } paint(); const settled = !s.drag && s.goal == null && Math.abs(s.vel) < 4 && s.pos <= 0.3 && s.pos >= lo - 0.3; if (settled) { s.pos = Math.min(0, Math.max(lo, s.pos)); paint(); s.raf = 0; } else s.raf = requestAnimationFrame(frame); }; s.raf = requestAnimationFrame(frame); }; useEffect(() => () => cancelAnimationFrame(st.current.raf), []); const down = (e: ReactPointerEvent) => { const s = st.current; s.drag = {x: e.clientX, pos: s.pos, t: performance.now()}; s.vel = 0; s.goal = null; rail.current!.setPointerCapture(e.pointerId); run(); }; const move = (e: ReactPointerEvent) => { const s = st.current; if (!s.drag) return; const now = performance.now(), lo = bounds(); let next = s.drag.pos + e.clientX - s.drag.x; if (next > 0) next *= 0.35; // 拖过头有阻力 if (next < lo) next = lo + (next - lo) * 0.35; s.vel = ((next - s.pos) / Math.max(1, now - s.drag.t)) * 1000; s.drag.t = now; s.pos = next; paint(); }; const up = () => { st.current.drag = null; run(); }; const key = (e: KeyboardEvent) => { if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return; e.preventDefault(); const s = st.current, step = ITEM + GAP; s.goal = Math.min(0, Math.max(bounds(), Math.round(((s.goal ?? s.pos) + (e.key === 'ArrowLeft' ? step : -step)) / step) * step)); run(); }; return (
{MORE.map((n, i) => (
{String(i + 3).padStart(2, '0')}
))}
); } export default function CursorLabelDemo() { return (