# 变形光标 Morph Cursor > 平时是半透明小圆点,靠近按钮时变成按钮的形状把它整个包住,离开弹回小圆点。 分类:鼠标特效 · 角色:点缀(贴在某个元素上,一页两三个) [全部组件和流程](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. 告诉用户用了什么、放在哪个文件、以后想改快慢、颜色、大小改哪个参数。 ## 什么时候用 - 适合:按钮和菜单多、偏工具感的产品:平板风格的应用、SaaS 官网、作品集的导航区。 - 不适合:按钮很少的页面(效果出不来);表单很多、要精确点击的后台;同一页已经有别的自定义光标。 - 适合的网站:SaaS、官网、作品集 - 放在:全站、按钮、导航 - 手机上:没效果:手机上什么都不加。 - 性能代价:低:鼠标进来时量一次按钮位置,光标只改大小和位置。 - 常搭配:[标签页 Tabs](https://www.dachuiai.com/c/tabs.md)、[顶部导航栏 Navbar](https://www.dachuiai.com/c/navbar.md) ## 装进项目 - 写法:React 18 以上 + TypeScript + Tailwind CSS v4,一个文件就能用,不引用别的组件。 - 依赖:`npm i lucide-react` - 文件:原样存成 `morph-cursor.tsx`(比如 `src/components/morph-cursor.tsx`)。能跑命令就下载[原文](https://www.dachuiai.com/code/morph-cursor.tsx),比手抄准:`curl -fsSL -o src/components/morph-cursor.tsx https://www.dachuiai.com/code/morph-cursor.tsx`(Windows 写 `curl.exe`)。下载完看一眼第一行是 `import`,不是网页。 - 导出:`MorphCursor` 是可以直接用的部分;最后的 `export default` 是演示示例,只作参考。 - 注意:被包住的按钮自己的 transform 会被盖掉,要旋转、缩放就在外面再包一层;selector 决定哪些元素会被包住,默认 button、a 和 [data-morph]。别和 magnetic 一起用(都会挪按钮)。 - 保留代码里 `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` | | 包在里面的内容 | | `dot` | `24` | 小圆点的直径(px) | | `pad` | `8` | 包住按钮时四边多出来几像素 | | `near` | `12` | 鼠标离按钮多近就开始包(px) | | `lean` | `0.07` | 按钮朝鼠标偏多少,0 就不偏 | | `tint` | `'70,70,82'` | 光标的颜色,写成 "r,g,b" | | `selector` | `'button, a, [data-morph]'` | 哪些元素会被包住 | | `className` | `''` | 加在最外层的类名,用来调大小、位置、间距 | ## 你可以说 > 自定义光标:靠近按钮时,光标变成按钮的大小和圆角,把它整个包住,离开再变回小圆点,用弹簧过渡。 ## 完整代码 ```tsx import {useEffect, useRef, useState, type ReactNode} from 'react'; import {Bookmark, CalendarDays, Check, Ellipsis, House, Play, Plus, Search, User} from 'lucide-react'; /* --------------------------------------------------------------- * MorphCursor 变形光标 * 平时是一个半透明的小圆点;靠近按钮时变成按钮的大小和圆角,比按钮大一圈把它整个包住, * 还会朝鼠标偏一点,按钮也跟着微微挪过来;离开再弹回小圆点。全程弹簧过渡。 * 默认 button、a 和加了 data-morph 的元素都会被包住(selector 可以改)。 * 只在这块区域里替换光标;手机、平板上什么都不加。开了「减弱动态效果」直接变形、不弹,按钮也不挪。 * dot:小圆点的直径(px) * pad:包住按钮时四边多出来几像素 * near:鼠标离按钮多近就开始包(px) * lean:按钮朝鼠标偏多少,0 就不偏 * tint:光标的颜色,写成 "r,g,b" * selector:哪些元素会被包住 * 注意:被包住的按钮自己的 transform 会被盖掉,要旋转、缩放就在外面再包一层。 * ------------------------------------------------------------- */ type Props = {children: ReactNode; dot?: number; pad?: number; near?: number; lean?: number; tint?: string; selector?: string; className?: string}; type Spring = {x: number; v: number; to: number; k: number; c: number}; export function MorphCursor({children, dot = 24, pad = 8, near = 12, lean = 0.07, tint = '70,70,82', selector = 'button, a, [data-morph]', className = ''}: Props) { const root = useRef(null); const shape = useRef(null); const [on, setOn] = useState(false); useEffect(() => { if (!matchMedia('(pointer: fine)').matches) return; setOn(true); const el = root.current!, cur = shape.current!; const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches; const spring = (x: number, k: number, c: number): Spring => ({x, v: 0, to: x, k, c}); const S = {x: spring(0, 520, 38), y: spring(0, 520, 38), w: spring(dot, 300, 24), h: spring(dot, 300, 24), r: spring(dot / 2, 300, 26)}; type Target = {el: HTMLElement; x: number; y: number; w: number; h: number; r: number; tx: number; ty: number; s: number}; let targets: Target[] = []; const m = {x: 0, y: 0, in: false}; let raf = 0, prev = 0, fresh = true, alpha = 0.38, wrap = 0, shown = 0; // 量出每个按钮在区域里的位置和圆角(量之前先拿掉偏移) const measure = () => { const box = el.getBoundingClientRect(); targets = [...el.querySelectorAll(selector)].map((t) => { const old = targets.find((o) => o.el === t); t.style.transform = ''; const r = t.getBoundingClientRect(), cs = getComputedStyle(t).borderTopLeftRadius; const radius = cs.endsWith('%') ? (parseFloat(cs) / 100) * r.width : parseFloat(cs) || 0; return {el: t, x: r.left - box.left, y: r.top - box.top, w: r.width, h: r.height, r: radius, tx: old?.tx ?? 0, ty: old?.ty ?? 0, s: old?.s ?? 1}; }).filter((t) => t.w > 0); }; const frame = (now: number) => { const dt = Math.min(0.05, Math.max(0, now - prev) / 1000); prev = now; let hit: Target | null = null, best = Infinity; if (m.in) for (const t of targets) { if (m.x < t.x - near || m.x > t.x + t.w + near || m.y < t.y - near || m.y > t.y + t.h + near) continue; const d = Math.hypot(m.x - (t.x + t.w / 2), m.y - (t.y + t.h / 2)); if (d < best) { best = d; hit = t; } } if (hit) { const cx = hit.x + hit.w / 2, cy = hit.y + hit.h / 2, h = hit.h + pad * 2; S.x.to = cx + (m.x - cx) * 0.12; S.y.to = cy + (m.y - cy) * 0.12; S.w.to = hit.w + pad * 2; S.h.to = h; S.r.to = Math.min(hit.r + pad, h / 2); } else { S.x.to = m.x; S.y.to = m.y; S.w.to = dot; S.h.to = dot; S.r.to = dot / 2; } const ease = (rate: number) => (reduce ? 1 : 1 - Math.exp(-rate * dt)); let moving = false; for (const s of Object.values(S)) { if (reduce) { s.x = s.to; s.v = 0; continue; } for (let i = 0, n = Math.ceil(dt / 0.004), h = dt / n; i < n; i++) { s.v += (-s.k * (s.x - s.to) - s.c * s.v) * h; s.x += s.v * h; } moving = moving || Math.abs(s.x - s.to) > 0.05 || Math.abs(s.v) > 0.05; } alpha += ((hit ? 0.2 : 0.38) - alpha) * ease(14); wrap += ((hit ? 1 : 0) - wrap) * ease(14); shown += ((m.in ? 1 : 0) - shown) * ease(14); const w = Math.max(8, S.w.x), h = Math.max(8, S.h.x); // 宽高直接改:光标本身很小,变形就是在改它的大小和圆角 cur.style.width = `${w}px`; cur.style.height = `${h}px`; cur.style.borderRadius = `${Math.max(4, Math.min(S.r.x, h / 2))}px`; cur.style.background = `rgba(${tint},${alpha.toFixed(3)})`; cur.style.opacity = shown.toFixed(3); // 包住时加一圈细线和一点投影,什么颜色的按钮上都看得出形状 cur.style.boxShadow = `0 0 0 1.5px rgba(${tint},${(0.26 * wrap).toFixed(3)}), 0 12px 26px rgba(28,28,30,${(0.14 * wrap).toFixed(3)})`; cur.style.transform = `translate(${S.x.x - w / 2}px, ${S.y.x - h / 2}px)`; // 被包住的按钮朝鼠标偏一点、稍微抬起来 for (const t of targets) { const hot = t === hit && !reduce; t.tx += ((hot ? (m.x - (t.x + t.w / 2)) * lean : 0) - t.tx) * ease(16); t.ty += ((hot ? (m.y - (t.y + t.h / 2)) * lean : 0) - t.ty) * ease(16); t.s += ((hot ? 1 + lean * 0.6 : 1) - t.s) * ease(16); const rest = Math.abs(t.tx) + Math.abs(t.ty) + Math.abs(t.s - 1) < 0.002; t.el.style.transform = rest ? '' : `translate(${t.tx.toFixed(2)}px, ${t.ty.toFixed(2)}px) scale(${t.s.toFixed(4)})`; moving = moving || !rest; } moving = moving || Math.abs(shown - (m.in ? 1 : 0)) > 0.002 || Math.abs(wrap - (hit ? 1 : 0)) > 0.002; raf = moving || m.in ? requestAnimationFrame(frame) : 0; }; const kick = () => { if (!raf) { prev = performance.now(); raf = requestAnimationFrame(frame); } }; const enter = (e: PointerEvent) => { if (e.pointerType !== 'touch') measure(); }; 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; S.x.x = m.x; S.y.x = m.y; } kick(); }; const leave = () => { m.in = false; fresh = true; kick(); }; const ro = new ResizeObserver(measure); ro.observe(el); el.addEventListener('pointerenter', enter); el.addEventListener('pointermove', move); el.addEventListener('pointerleave', leave); return () => { cancelAnimationFrame(raf); ro.disconnect(); el.removeEventListener('pointerenter', enter); el.removeEventListener('pointermove', move); el.removeEventListener('pointerleave', leave); for (const t of targets) t.el.style.transform = ''; }; }, [dot, pad, near, lean, tint, selector]); return (
{children}
); } /* ---------------- 示例:平板上的待办应用 ---------------- */ const TABS = ['全部', '工作', '生活', '灵感']; const TOOLS = [{label: '搜索', icon: Search}, {label: '新建', icon: Plus}, {label: '更多', icon: Ellipsis}]; const DOCK = [ {label: '首页', icon: House, color: '#2F6BFF'}, {label: '日历', icon: CalendarDays, color: '#FF9F45'}, {label: '已完成', icon: Check, color: '#34C7A0'}, {label: '收藏', icon: Bookmark, color: '#B45CFF'}, {label: '我的', icon: User, color: '#55555E'}, ]; const ring = 'outline-none focus-visible:ring-2 focus-visible:ring-[#2F6BFF] focus-visible:ring-offset-2 focus-visible:ring-offset-[#F0F0F5]'; export default function MorphCursorDemo() { const [tab, setTab] = useState('全部'); const [focus, setFocus] = useState(false); return (

今天

周四 · 还有 3 件事

{TOOLS.map(({label, icon: Icon}) => ( ))}
{TABS.map((t) => ( ))}

本周重点

把首页做完

还差导航和结尾两块,预计 40 分钟

68%已完成
); } ```