# 聚光灯卡片（Spotlight card）

- 俗称：鼠标在卡片上移动，有一团光跟着走；卡片上的光跟着鼠标；鼠标放上去，卡片那一块会发光；鼠标经过卡片时那一块变亮；像手电筒照在卡片上
- 用在：卡片列表（作品集、品牌官网、博物馆和展览）
- 触发：悬停
- 感觉：高级、科技感
- 版本：1，更新于 2026-10-15

## 原理

卡片的背景上叠一层径向渐变的光，光的中心跟着鼠标的位置走；鼠标进来时光淡入，离开时淡出。

适合：作品卡片、功能卡片、价格卡片：鼠标经过时像展柜里的灯照着，提示"这张能点"，又不改变卡片的排版。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `size` | 光斑直径 | 260px | 120–800px |
| `intensity` | 光的亮度 | 24% | 4–50% |
| `duration` | 淡入淡出时长 | 300ms | 0–800ms |
| `easing` | 缓动 | cubic-bezier(0.4, 0, 0.2, 1) | — |

## 质量要求

- 开启"减少动态"时：光照样跟着鼠标（是用户自己在移动），出现和消失不做淡入淡出。
- 手机上：手机上没有悬停：手指按住的地方亮起，松开后淡出；拖动照常滚动页面。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

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

```text
请在我的项目里给卡片列表加上「聚光灯卡片」（Spotlight card）效果：卡片的背景上叠一层径向渐变的光，光的中心跟着鼠标的位置走；鼠标进来时光淡入，离开时淡出。
参数：光斑直径 260px，光的亮度 24%，淡入淡出时长 300ms，缓动 cubic-bezier(0.4, 0, 0.2, 1)。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/spotlight-card.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<!-- 聚光灯卡片：给要加光的卡片标上 data-spotlight，脚本会给它加上 class="spotlight" 和一层光 -->
<div class="cards">
  <a class="card" href="/works/1" data-spotlight>
    <h3>作品一</h3>
    <p>一句话介绍</p>
  </a>
  <a class="card" href="/works/2" data-spotlight>
    <h3>作品二</h3>
    <p>一句话介绍</p>
  </a>
</div>
<script type="module">
  import { spotlight } from './spotlight.js';
  spotlight(document.querySelectorAll('[data-spotlight]'));
</script>
```

CSS：

```css
/* 聚光灯卡片（Spotlight card）的样式，配合 spotlight.js。--spot-x、--spot-y、--spot-size、--spot-intensity 由脚本设置。
   光在卡片的背景上面、内容下面：isolation 让卡片自成一层，光的 z-index: -1 只沉到卡片背景上面，不会沉到页面后面去；
   文字压在光上面，不会被光冲淡。光的圆角跟着卡片，卡片不用 overflow: hidden。
   跟着鼠标变的只有位置变量，只影响光这一层的背景，不会引起重新排版。
   光默认是白色，适合深色卡片；浅色卡片把 --spot-color 换成主题色或深一点的颜色。
   卡片要有定位（光按它来摆）：原来没有定位的，脚本会补上 position: relative；原来是 absolute、sticky 的不动。 */
.spotlight { isolation: isolate; }
.spotlight-glow {
  position: absolute;
  inset: 0;
  z-index: -1;
  border-radius: inherit;
  pointer-events: none;
  opacity: 0;
  background: radial-gradient(circle calc(var(--spot-size) / 2) at var(--spot-x) var(--spot-y), var(--spot-color, #fff), transparent);
}
.spotlight.is-lit .spotlight-glow { opacity: var(--spot-intensity); }
```

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

```js
// 聚光灯卡片（Spotlight card）· 原生 JS，不依赖任何库。
// 改写自 StyleKit 的 spotlight-card（MIT License，Copyright (c) 2026 AnxForever）：做法（卡片上叠一层径向渐变的光，中心跟着鼠标）和进出时的淡入淡出来自它。
// cards 是一张或一组卡片（配合 spotlight.css）。鼠标在卡片上移动时，一团柔光跟着走；鼠标进来时光淡入，离开时淡出。
// 返回 { show(card, x, y), move(card, x, y), hide(card), destroy() }，坐标是相对卡片内边框左上角的像素；
// show、hide 返回的 Promise 在淡入、淡出播完（或被打断）后结束。
// 开启"减少动态"时：光照样跟着鼠标（是用户自己在移动），出现和消失不做淡入淡出。
// 脚本出错或没执行时：卡片原样显示，只是没有光。手机上没有悬停：手指按住的地方亮起，松开后淡出。
// ignoreReducedMotion 只给"用户主动点播放"的演示用，网站自己的卡片不要打开它。
export function spotlight(cards, {
  size = 260,
  intensity = 24,
  duration = 300,
  easing = 'cubic-bezier(0.4, 0, 0.2, 1)',
  ignoreReducedMotion = false,
} = {}) {
  const reduce = !ignoreReducedMotion && matchMedia('(prefers-reduced-motion: reduce)').matches;
  const list = cards instanceof Element ? [cards] : [...cards];
  const level = intensity / 100;
  const fade = [{ opacity: 0 }, { opacity: level }];
  const state = new Map();

  const move = (card, x, y) => {
    card.style.setProperty('--spot-x', `${x}px`);
    card.style.setProperty('--spot-y', `${y}px`);
  };
  // 淡入、淡出：还没播完又反过来时，从当前的亮度倒回去，不跳
  const turn = (card, frames) => {
    const s = state.get(card);
    if (s.anim && s.anim.playState === 'running') s.anim.reverse();
    else s.anim = s.glow.animate(frames, { duration, easing });
    return s.anim.finished.then(() => undefined, () => undefined);
  };
  const show = (card, x, y) => {
    move(card, x, y);
    if (card.classList.contains('is-lit')) return Promise.resolve();
    card.classList.add('is-lit');
    return reduce ? Promise.resolve() : turn(card, fade);
  };
  const hide = (card) => {
    if (!card.classList.contains('is-lit')) return Promise.resolve();
    card.classList.remove('is-lit');
    return reduce ? Promise.resolve() : turn(card, [...fade].reverse());
  };

  // 鼠标位置换成卡片里的像素：卡片被缩放过也对（横竖分开算），再减掉边框，和光的坐标对齐
  const local = (card, e) => {
    const r = card.getBoundingClientRect();
    const kx = r.width ? card.offsetWidth / r.width : 1;
    const ky = r.height ? card.offsetHeight / r.height : 1;
    return [(e.clientX - r.left) * kx - card.clientLeft, (e.clientY - r.top) * ky - card.clientTop];
  };
  const listeners = (card) => [
    ['pointerenter', (e) => { if (e.pointerType !== 'touch') show(card, ...local(card, e)); }],
    ['pointermove', (e) => { if (e.pointerType !== 'touch' || card.classList.contains('is-lit')) move(card, ...local(card, e)); }],
    ['pointerleave', (e) => { if (e.pointerType !== 'touch') hide(card); }],
    ['pointerdown', (e) => { if (e.pointerType === 'touch') show(card, ...local(card, e)); }],
    ['pointerup', (e) => { if (e.pointerType === 'touch') hide(card); }],
    ['pointercancel', (e) => { if (e.pointerType === 'touch') hide(card); }],
  ];

  list.forEach((card) => {
    const glow = document.createElement('span');
    glow.className = 'spotlight-glow';
    glow.setAttribute('aria-hidden', 'true');
    // 光按卡片来摆：卡片没有定位时补上 relative（不改变位置）；原来是 absolute、sticky 的不动
    const position = card.style.position;
    if (getComputedStyle(card).position === 'static') card.style.position = 'relative';
    card.classList.add('spotlight');
    card.style.setProperty('--spot-size', `${size}px`);
    card.style.setProperty('--spot-intensity', String(level));
    card.append(glow);
    const events = listeners(card);
    events.forEach(([type, fn]) => card.addEventListener(type, fn));
    state.set(card, { glow, anim: null, events, position });
  });

  return {
    show,
    move,
    hide,
    destroy() {
      state.forEach(({ glow, anim, events, position }, card) => {
        anim?.cancel();
        events.forEach(([type, fn]) => card.removeEventListener(type, fn));
        glow.remove();
        card.style.position = position;
        card.classList.remove('spotlight', 'is-lit');
        ['--spot-x', '--spot-y', '--spot-size', '--spot-intensity'].forEach((name) => card.style.removeProperty(name));
      });
      state.clear();
    },
  };
}
```

## 出处

- StyleKit · Spotlight Card（https://github.com/AnxForever/stylekit/blob/main/lib/animations/_legacy/spotlight-card.ts，MIT）：改写自它的做法和默认值（卡片上叠一层白色径向光，中心跟着鼠标；进出时 300ms 淡入淡出）；改成原生 JS，光放在内容下面，不用 overflow: hidden；加了手机上按住亮起；光斑大小和亮度改成参数
