# 链接悬停预览（Link preview）

- 俗称：鼠标放在链接上，弹出那一页的预览图；链接悬停显示缩略图；正文里的链接停一下就冒出一张小图；悬停预览链接的页面
- 用在：正文（博客、个人网站、作品集）
- 触发：悬停
- 感觉：俏皮、利落
- 版本：1，更新于 2026-10-19

## 原理

鼠标在链接上停一会儿，链接上方弹出一张预览图（自己准备的封面），从小放大、冲过头一点再回来，横向跟着鼠标走；鼠标离开链接和预览图时收起。

适合：文章正文里指向自己别的文章、作品的链接：不用点开就知道链到哪里，读的人更愿意点。导航和按钮不用它。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `delay` | 停多久才弹出 | 250ms | 0–800ms |
| `duration` | 弹出时长 | 450ms | 150–1000ms |
| `easing` | 缓动 | cubic-bezier(0.34, 1.56, 0.64, 1) | — |

## 质量要求

- 开启"减少动态"时：预览图照样在停一会儿后出现，但直接出现、直接消失，不做放大。
- 手机上：手机上没有悬停：不弹预览，点链接直接打开（预览只是锦上添花，不能挡住点链接）。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

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

```text
请在我的项目里给正文加上「链接悬停预览」（Link preview）效果：鼠标在链接上停一会儿，链接上方弹出一张预览图（自己准备的封面），从小放大、冲过头一点再回来，横向跟着鼠标走；鼠标离开链接和预览图时收起。
参数：停多久才弹出 250ms，弹出时长 450ms，缓动 cubic-bezier(0.34, 1.56, 0.64, 1)。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/link-preview.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<!-- 链接悬停预览：给正文里想预览的链接加上 data-preview（自己准备的封面图），一组调用一次 -->
<p>
  上个月写了一篇
  <a href="/posts/breathing-opening" data-preview="/covers/breathing-opening.webp">怎么做一个会呼吸的开屏</a>，
  里面的圆环后来也用在了作品集上。
</p>
<script type="module">
  import { linkPreview } from './link-preview.js';
  linkPreview(document.querySelectorAll('a[data-preview]'));
</script>
```

CSS：

```css
/* 链接悬停预览（Link preview）的样式，配合 link-preview.js。预览图（.lp-card）由脚本放进链接里，位置由脚本算好写在 left、top 上。
   颜色、大小按自己的网站改：卡片宽 200px，图片 16:10。图片还没加载完时先显示底色。
   卡片和链接之间空着 10px（脚本里的 GAP），::before 是盖住这段空隙的"桥"：鼠标从链接挪到卡片上的途中不算离开。 */
.lp-card {
  position: absolute;
  z-index: 10;
  display: none;
  width: 200px;
  padding: 4px;
  border-radius: 12px;
  background: #fff;
  box-shadow: 0 14px 30px -12px rgb(0 0 0 / 0.4), 0 0 0 1px rgb(0 0 0 / 0.06);
}
.lp-card.is-open { display: block; }
.lp-card img { display: block; width: 100%; aspect-ratio: 16 / 10; border-radius: 9px; object-fit: cover; background: #eef0ee; }
.lp-card::before { content: ""; position: absolute; left: 0; right: 0; top: 100%; height: 10px; }
.lp-card.is-below::before { top: auto; bottom: 100%; }
```

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

```js
// 链接悬停预览（Link preview）· 原生 JS，不依赖任何库。
// 改写自 Inspira UI 的 LinkPreview.vue（MIT License，Copyright (c) 2024-2026 rahulv.dev；它移植自 Aceternity UI 的 Link Preview）：
// 做法来自它——鼠标停在链接上，链接上方弹出一张预览图，横向跟着鼠标走、不出屏幕，弹出时从小放大、冲过头一点再回来。
// links 是一个或一组链接（配合 link-preview.css），每个链接用 data-preview 写预览图的地址（自己准备的封面，不用第三方截图服务）。
// 鼠标在链接上停 delay 毫秒后弹出预览图，从 60% 放大到原大、透明到不透明（duration、easing；默认的缓动会冲过头一点再回来）；
// 鼠标离开链接和预览图时收起。键盘选中链接时也弹出（在链接正上方），移走焦点时收起；按 Esc 随时收起（焦点在哪里都行，鼠标不用挪开）。
// 预览图放在链接里面（aria-hidden，读屏不读）：鼠标从链接挪到预览图上不会消失，点预览图就是点这个链接。
// 预览图按链接最近的定位祖先摆放（position: absolute），横向不出这个祖先和屏幕；上面放不下（被屏幕、或者外面 overflow 不是 visible 的框挡住）
// 就弹在链接下面，上下都放不下时弹在空得多的那一边——框比预览图还小时总会被裁一截，把预览图改小（link-preview.css 的 width）。
// 返回 { show(link, x), hide(link), destroy() }：x 是鼠标在屏幕上的横坐标（clientX），不传就摆在链接正上方。
// 开启"减少动态"时：照样停一会儿后出现，但直接出现、直接消失，不放大。脚本没执行时链接照常能点，只是没有预览。
// 手机上没有悬停：不弹预览，点链接直接打开。
// listen 为 false 时不监听鼠标和键盘，只用 show / hide 自己控制（演示用）。ignoreReducedMotion 只给演示用，网站自己的链接不要打开它。
export function linkPreview(links, {
  delay = 250,
  duration = 450,
  easing = 'cubic-bezier(0.34, 1.56, 0.64, 1)',
  listen = true,
  ignoreReducedMotion = false,
} = {}) {
  const reduce = !ignoreReducedMotion && matchMedia('(prefers-reduced-motion: reduce)').matches;
  const list = links instanceof Element ? [links] : [...links];
  const GAP = 10; // 预览图和链接之间的空隙（屏幕上的像素），link-preview.css 里的桥要和它一样高
  const state = new Map(list.map((link) => [link, { card: null, anim: null, timer: 0, open: false, closing: false }]));

  // 第一次用到时才建预览图（图片这时才开始加载）
  const cardOf = (link) => {
    const s = state.get(link);
    if (!s.card) {
      s.card = document.createElement('span');
      s.card.className = 'lp-card';
      s.card.setAttribute('aria-hidden', 'true');
      const img = document.createElement('img');
      img.alt = '';
      img.decoding = 'async';
      img.src = link.dataset.preview ?? '';
      s.card.append(img);
      link.append(s.card);
    }
    return s.card;
  };

  // 上下能摆到哪里：屏幕，和从定位祖先往外、会裁掉内容（overflow 不是 visible）的框，取它们重叠的那一段
  const room = (parent) => {
    let [top, bottom] = [0, innerHeight];
    for (let el = parent; el && el !== document.body && el !== document.documentElement; el = el.parentElement) {
      const cs = getComputedStyle(el);
      if (cs.overflowX === 'visible' && cs.overflowY === 'visible') continue;
      const r = el.getBoundingClientRect();
      [top, bottom] = [Math.max(top, r.top), Math.min(bottom, r.bottom)];
    }
    return [top, bottom];
  };
  // 摆在链接上方：横向对着鼠标（没有鼠标就对着链接的中间），不出定位祖先的框、不出屏幕；上面放不下就摆在下面，都放不下摆在空得多的一边。
  // 链接折成几行时，对着鼠标所在的那一行。坐标先在屏幕上算，再换成定位祖先里的像素（外面有缩放时也对）
  const place = (link, card, x) => {
    const parent = card.offsetParent ?? document.body;
    const pr = parent.getBoundingClientRect();
    const k = pr.width ? parent.offsetWidth / pr.width : 1;
    const rects = [...link.getClientRects()].filter((r) => r.width > 0);
    const line = (x !== undefined && rects.find((r) => x >= r.left && x <= r.right)) || rects[0] || link.getBoundingClientRect();
    const [w, h] = [card.offsetWidth / k, card.offsetHeight / k];
    const cx = x ?? (line.left + line.right) / 2;
    const left = Math.max(Math.max(pr.left, 0) + 4, Math.min(cx - w / 2, Math.min(pr.right, innerWidth) - 4 - w));
    const [roomTop, roomBottom] = room(parent);
    const [up, down] = [line.top - GAP - roomTop, roomBottom - line.bottom - GAP];
    const below = up < h && (down >= h || down > up);
    const top = below ? line.bottom + GAP : line.top - GAP - h;
    card.classList.toggle('is-below', below);
    card.style.left = `${(left - pr.left) * k - parent.clientLeft + parent.scrollLeft}px`;
    card.style.top = `${(top - pr.top) * k - parent.clientTop + parent.scrollTop}px`;
    // 从对着鼠标的那一点（卡片靠链接的那条边上）放大出来
    card.style.transformOrigin = `${(Math.min(Math.max(cx - left, 0), w) * k).toFixed(1)}px ${below ? '0%' : '100%'}`;
  };

  const show = (link, x) => {
    const s = state.get(link);
    const card = cardOf(link);
    // 已经弹出（或正在弹、正在等）：只跟着鼠标挪；正在收起时又回来了，收起的动画取消，接着显示
    if (s.open) {
      if (s.closing) { s.closing = false; s.anim?.cancel(); s.anim = null; }
      place(link, card, x);
      return;
    }
    s.open = true;
    card.classList.add('is-open');
    place(link, card, x);
    if (reduce) {
      card.style.visibility = 'hidden';
      s.timer = setTimeout(() => { card.style.visibility = ''; }, delay);
      return;
    }
    s.anim = card.animate([{ opacity: 0, scale: 0.6 }, { opacity: 1, scale: 1 }], { duration, delay, easing, fill: 'backwards' });
  };
  const hide = (link) => {
    const s = state.get(link);
    if (!s?.open || s.closing) return;
    clearTimeout(s.timer);
    const card = s.card;
    const close = () => { card.classList.remove('is-open'); card.style.visibility = ''; s.anim = null; s.open = false; s.closing = false; };
    // 还在等、还在弹的时候就离开了：从现在的样子淡出；还没露面（停的时间不够）就直接收起
    const cs = getComputedStyle(card);
    const from = { opacity: Number(cs.opacity), scale: cs.scale === 'none' ? 1 : Number(cs.scale.split(' ')[0]) };
    s.anim?.cancel();
    if (reduce || from.opacity === 0 || card.style.visibility === 'hidden') { close(); return; }
    s.closing = true;
    s.anim = card.animate([from, { opacity: 0, scale: 0.96 }], { duration: 150, easing: 'ease-in' });
    // 播完收起；被别人取消（比如整页的动画被停掉）也收起，被 show 取消（又回来了）不收
    s.anim.finished.then(close, () => { if (s.closing) close(); });
  };

  const events = [];
  const on = (target, type, fn) => { target.addEventListener(type, fn); events.push([target, type, fn]); };
  if (listen) {
    list.forEach((link) => {
      on(link, 'pointerenter', (e) => { if (e.pointerType !== 'touch') show(link, e.clientX); });
      // 鼠标在链接的字上移动时，预览图横向跟着走；挪到预览图上时不动
      on(link, 'pointermove', (e) => {
        const { card, open } = state.get(link);
        if (e.pointerType !== 'touch' && open && !card.contains(e.target)) place(link, card, e.clientX);
      });
      on(link, 'pointerleave', (e) => { if (e.pointerType !== 'touch' && !link.matches(':focus-visible')) hide(link); });
      on(link, 'focus', () => { if (link.matches(':focus-visible')) show(link); });
      on(link, 'blur', () => hide(link));
    });
    // Esc 收起（WCAG 1.4.13：鼠标停着弹出来的东西，要能不挪鼠标就关掉）：焦点在哪里都行；收起以后鼠标在链接上挪不会再弹，离开再回来才弹
    on(document, 'keydown', (e) => { if (e.key === 'Escape') state.forEach((s, link) => { if (s.open) hide(link); }); });
  }

  return {
    show,
    hide,
    destroy() {
      events.forEach(([target, type, fn]) => target.removeEventListener(type, fn));
      state.forEach((s) => { clearTimeout(s.timer); s.anim?.cancel(); s.card?.remove(); });
      state.clear();
    },
  };
}
```

## 出处

- Inspira UI · Link Preview（移植自 Aceternity UI 的 Link Preview）（https://github.com/unovue/inspira-ui/blob/main/app/components/inspira/ui/link-preview/LinkPreview.vue，MIT）：改写自它的做法（鼠标停在链接上，上方弹出预览图，横向跟着鼠标、不出屏幕；从小放大、冲过头一点再回来）；用原生 JS 重写（原版是 Vue），预览图改用自己的封面、不用第三方截图服务，加了停一会儿才弹、预览图放在链接里（挪上去不消失、点它也能打开）、键盘选中时弹出、按 Esc 收起、上面放不下时弹在下面
