# 光标跟随光圈（Cursor follower）

- 俗称：一个圆圈跟着鼠标走；鼠标后面拖着一个光圈；自定义光标跟随；鼠标经过链接时光圈放大
- 用在：背景（个人网站、作品集）
- 触发：悬停
- 感觉：高级、科技感
- 版本：1，更新于 2026-11-05

## 原理

在区域里放一个圆圈（aria-hidden、不挡点击），鼠标移动时把圈的位置交给一个 CSS 过渡，它自己从现在的位置慢半拍追过去；鼠标移到链接、按钮上时用 scale 放大；第一次进来时直接出现在鼠标那里，不从别处飞过来；保留系统光标；只在有鼠标的设备上工作；减少动态时没有追赶的延迟。

适合：创意类的个人主页、作品集首屏：鼠标后面拖着一个圈，慢半拍追上来，移到可以点的东西上圈就放大，页面显得更"活"。手机上没有鼠标，不显示。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `size` | 光圈直径 | 36px | 16–80px |
| `lag` | 跟上鼠标要多久 | 180ms | 60–500ms |
| `grow` | 经过链接时放大几倍 | 1.6倍 | 1–3倍 |

## 质量要求

- 开启"减少动态"时：光圈没有追赶的延迟，直接待在鼠标的位置；放大照常（只是一个状态）。
- 手机上：手机、平板没有鼠标，不显示光圈、不加监听。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

## 提示词（可以直接交给 AI）

```text
请在我的项目里给背景加上「光标跟随光圈」（Cursor follower）效果：在区域里放一个圆圈（aria-hidden、不挡点击），鼠标移动时把圈的位置交给一个 CSS 过渡，它自己从现在的位置慢半拍追过去；鼠标移到链接、按钮上时用 scale 放大；第一次进来时直接出现在鼠标那里，不从别处飞过来；保留系统光标；只在有鼠标的设备上工作；减少动态时没有追赶的延迟。
参数：光圈直径 36px，跟上鼠标要多久 180ms，经过链接时放大几倍 1.6倍。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/cursor-follower.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<!-- 光标跟随光圈：给要显示光圈的区域（通常是首屏）调用一次；区域要有定位。链接、按钮上光圈会放大；别的元素想放大就加 data-cursor-grow -->
<section class="hero" id="hero" style="position: relative">
  <h1>你好，我是北煜ii</h1>
  <a href="/works/">看作品</a>
  <span data-cursor-grow>这里也会放大</span>
</section>
<script type="module">
  import { cursorFollower } from './cursor-follower.js';
  cursorFollower(document.getElementById('hero'), { size: 36, lag: 180, grow: 1.6 });
</script>
```

CSS：

```css
/* 光标跟随光圈的样式，配合 cursor-follower.js。光圈的直径、追上鼠标的时长由脚本写在区域的 --cf-size、--cf-lag 上；
   颜色跟着文字颜色（区域里写 color 就能换）。开启"减少动态"时没有追赶的延迟、放大不过渡（演示强制播放时区域有 data-cf-motion，就不关）。 */
.cf-ring {
  position: absolute;
  left: 0;
  top: 0;
  width: var(--cf-size, 36px);
  height: var(--cf-size, 36px);
  margin: calc(var(--cf-size, 36px) / -2) 0 0 calc(var(--cf-size, 36px) / -2);
  border: 2px solid currentColor;
  border-radius: 50%;
  box-sizing: border-box;
  pointer-events: none;
  opacity: 0;
  transition: translate var(--cf-lag, 180ms) ease-out, scale 150ms ease-out, opacity 150ms;
}
@media (prefers-reduced-motion: reduce) {
  :not([data-cf-motion]) > .cf-ring { transition: opacity 150ms; }
}
```

JS（原生，不依赖任何库）：

```js
// 光标跟随光圈（Cursor follower）· 原生 JS，不依赖任何库。
// 参考 StyleKit 的 cursor-aura、Animation Handbook 的 cursor-follower 的做法（都是 MIT），自己实现，没有复制代码。
// 用法：cursorFollower(区域元素)，返回 { move(x, y), hover(on), hide(), destroy() }（x、y 是相对区域左上角的位置；鼠标的事件内部也走这几个）。
// 区域要有定位（position 不是 static）：光圈是区域里的 position: absolute。区域是 static 时脚本给它加行内 position: relative，destroy() 时还原；
// 区域自己写了别的定位（relative、absolute、sticky）就用它的。除此以外脚本只在区域的行内写两个 CSS 变量（--cf-size、--cf-lag），destroy() 时还成装之前的样子。
// 区域自己有缩放（transform: scale）时光圈会追偏（坐标按缩放以后的框算、位移是局部像素）：别把它放在被缩放的元素里。
// 只在装上时读一次"有没有鼠标"的媒体查询（接上、拔掉鼠标不会重新判断）。
// 选项：size 光圈直径（px，默认 36）；lag 跟上鼠标要多久（毫秒，默认 180）；grow 鼠标在链接、按钮上时放大几倍（默认 1.6）。
// 光圈 <div class="cf-ring" aria-hidden="true">：不挡点击（pointer-events: none）、读屏读不到。位置用 translate 属性，交给 CSS 过渡去追：
// 每次移动只改 style.translate，过渡自己从现在的位置重新出发（不每次都新建动画）。光圈是藏着的（刚进来、hide() 之后）时，
// 这一次直接到位、不过渡（先关过渡、写位置、强制回流、再恢复），然后淡入——不会从上一次离开的地方飞过来。
// 鼠标移到 a、button、[role="button"]、input、textarea、select、summary、[data-cursor-grow] 上时放大（scale 属性），离开时缩回；
// 鼠标离开区域时淡出。只认鼠标（pointerType 是 mouse），触摸和笔不管。
// 只在有鼠标的设备上工作：(hover: hover) and (pointer: fine) 不满足（手机、平板）时返回一个什么都不做的控制对象，不建光圈、不加监听。
// 保留系统光标（不写 cursor: none：看不清光标的人更难用），光圈是在它旁边加的一圈。
// 开启"减少动态"时：没有追赶的延迟，光圈就在鼠标的位置，放大也不过渡（放大本身保留）；ignoreReducedMotion 只给演示强制播放用（给区域加 data-cf-motion）。
// destroy()：摘掉所有监听、移除光圈、清掉区域上的行内变量，之后 move、hover、hide 什么都不做；对同一个区域重复调用，先 destroy 旧的。

// 每个区域现在装着的控制对象（对同一个区域重复调用时先拆旧的）
const prevs = new WeakMap();
const GROW = 'a, button, [role="button"], input, textarea, select, summary, [data-cursor-grow]';

export function cursorFollower(area, {
  size = 36,
  lag = 180,
  grow = 1.6,
  ignoreReducedMotion = false,
} = {}) {
  prevs.get(area)?.destroy();
  const nothing = { move() {}, hover() {}, hide() {}, destroy() {} };
  if (!matchMedia('(hover: hover) and (pointer: fine)').matches) return nothing;

  // 区域没有定位（static）时给它加行内 position: relative：光圈是区域里的 position: absolute，不然会相对更外层的定位祖先摆、追偏。
  // 脚本动的三样（position、--cf-size、--cf-lag）装之前是什么，destroy() 就还成什么（页面事先写过同名的行内变量也不会被清掉）
  const keep = ['position', '--cf-size', '--cf-lag'].map((name) => [name, area.style.getPropertyValue(name), area.style.getPropertyPriority(name)]);
  const hadStyle = area.hasAttribute('style');
  if (getComputedStyle(area).position === 'static') area.style.position = 'relative';
  area.style.setProperty('--cf-size', `${size}px`);
  area.style.setProperty('--cf-lag', `${lag}ms`);
  if (ignoreReducedMotion) area.setAttribute('data-cf-motion', '');
  const ring = document.createElement('div');
  ring.className = 'cf-ring';
  ring.setAttribute('aria-hidden', 'true');
  area.append(ring);
  let shown = false;
  let dead = false;

  const ctl = {
    move(x, y) {
      if (dead) return;
      if (!shown) {
        // 藏着的时候：直接到位、不过渡，再淡入
        ring.style.transition = 'none';
        ring.style.translate = `${x}px ${y}px`;
        void ring.offsetWidth;
        ring.style.transition = '';
        ring.style.opacity = '1';
        shown = true;
        return;
      }
      ring.style.translate = `${x}px ${y}px`;
    },
    hover(on) {
      if (dead) return;
      ring.style.scale = on ? String(grow) : '';
    },
    hide() {
      if (dead) return;
      ring.style.opacity = '0';
      shown = false;
    },
    destroy() {
      if (dead) return;
      dead = true;
      for (const [type, fn] of listeners) area.removeEventListener(type, fn);
      ring.remove();
      for (const [name, value, priority] of keep) {
        if (value) area.style.setProperty(name, value, priority); else area.style.removeProperty(name);
      }
      // 装之前没有 style 属性的，摘完是空的就把属性去掉（Chrome 里写过样式的元素，读一次才会把空属性写回来，所以拿掉两次）
      if (!hadStyle && !area.getAttribute('style')) { area.removeAttribute('style'); if (area.getAttribute('style') !== null) area.removeAttribute('style'); }
      area.removeAttribute('data-cf-motion');
      if (prevs.get(area) === ctl) prevs.delete(area);
    },
  };

  // 鼠标位置换成区域里的坐标（区域的内边距框左上角起）
  const local = (e) => {
    const box = area.getBoundingClientRect();
    return [e.clientX - box.left - area.clientLeft, e.clientY - box.top - area.clientTop];
  };
  // 这个元素在不在区域里的某个"可以点的东西"里面
  const grows = (el) => {
    const hit = el instanceof Element ? el.closest(GROW) : null;
    return Boolean(hit && area.contains(hit));
  };
  const onMove = (e) => { if (e.pointerType === 'mouse') ctl.move(...local(e)); };
  const onOver = (e) => { if (e.pointerType === 'mouse') ctl.hover(grows(e.target)); };
  const onOut = (e) => { if (e.pointerType === 'mouse') ctl.hover(grows(e.relatedTarget)); };
  const onLeave = (e) => { if (e.pointerType === 'mouse') ctl.hide(); };
  const listeners = [['pointermove', onMove], ['pointerover', onOver], ['pointerout', onOut], ['pointerleave', onLeave]];
  for (const [type, fn] of listeners) area.addEventListener(type, fn);
  prevs.set(area, ctl);
  return ctl;
}
```

## 出处

- 参考 StyleKit cursor-aura、Animation Handbook cursor-follower 的做法（圆圈慢半拍追鼠标、经过链接放大），自己实现，没有复制代码；用 CSS 过渡追位置、第一次进来直接到位、保留系统光标、只在有鼠标的设备上工作、减少动态去掉延迟是本站自己定的
