# 共享元素过渡（Shared element transition）

- 俗称：点开卡片，卡片上的图变成详情页的大图；列表里的小图放大飞到详情页；缩略图平滑变成大图；点进去图片跟着过去
- 用在：页面切换、图片（作品集、博物馆和展览、电商）
- 触发：点击
- 感觉：柔和、高级
- 版本：1，更新于 2026-10-15

## 原理

切换前记下这张图的位置和大小；切换后，新画面里的同一张图从旧的位置出发，平滑移动、缩放到自己的位置（FLIP：记起点、量终点、反推回起点、播放）。

适合：列表进详情、相册、作品集：同一张图在前后两个画面里都有，让人看清"我点开的就是它"。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `duration` | 时长 | 500ms | 200–1200ms |
| `easing` | 缓动 | cubic-bezier(0.2, 0.7, 0.3, 1) | — |

## 质量要求

- 开启"减少动态"时：不做移动和缩放，直接切换到新的画面。
- 手机上：和桌面一样；手机上图片走的距离短，时长可以短一点。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

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

```text
请在我的项目里给页面切换加上「共享元素过渡」（Shared element transition）效果：切换前记下这张图的位置和大小；切换后，新画面里的同一张图从旧的位置出发，平滑移动、缩放到自己的位置（FLIP：记起点、量终点、反推回起点、播放）。
参数：时长 500ms，缓动 cubic-bezier(0.2, 0.7, 0.3, 1)。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/shared-element.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<!-- 共享元素过渡：点开列表里的一张图，详情里的大图从这张图的位置飞过来；返回时这张图从大图的位置飞回列表 -->
<ul class="covers">
  <li><button class="cover" type="button"><img src="cover-1.jpg" alt="第一张专辑"></button></li>
  <li><button class="cover" type="button"><img src="cover-2.jpg" alt="第二张专辑"></button></li>
</ul>
<section class="detail" hidden>
  <img class="hero" src="cover-1.jpg" alt="第一张专辑">
  <button class="back" type="button">返回</button>
</section>
<style>
  /* 大图先有确定的大小，图片还没加载完也量得到终点 */
  .hero { display: block; width: 100%; aspect-ratio: 1; object-fit: cover; }
</style>
<script type="module">
  import { sharedElement } from './shared-element.js';
  const covers = document.querySelector('.covers');
  const detail = document.querySelector('.detail');
  const hero = detail.querySelector('.hero');
  let opened = null;
  covers.addEventListener('click', (e) => {
    const cover = e.target.closest('.cover');
    if (!cover) return;
    const first = cover.getBoundingClientRect(); // 切换前：这张图在哪
    const img = cover.querySelector('img');
    hero.src = img.src;
    hero.alt = img.alt;
    covers.hidden = true;                        // 切换
    detail.hidden = false;
    opened = cover;
    sharedElement(first, hero);                  // 大图从这张图的位置飞过来
    detail.querySelector('.back').focus();
  });
  detail.querySelector('.back').addEventListener('click', () => {
    const first = hero.getBoundingClientRect();
    detail.hidden = true;
    covers.hidden = false;
    sharedElement(first, opened);                // 这张图从大图的位置飞回列表
    opened.focus();
  });
</script>
```

CSS：

```css
/* 共享元素过渡（Shared element transition）：用 FLIP 做（shared-element.js）只需要脚本，不需要额外的样式。
   要注意的只有一点：新元素要先有确定的大小（比如 aspect-ratio: 1），图片还没加载完时也量得到终点。

   另一种做法：单页应用切路由、或者多页网站点链接跳转时，可以交给浏览器原生的 View Transitions：
   1. 切换前被点的那张图、切换后的大图，设同一个 view-transition-name（同一时刻页面上只能有一个元素用这个名字）；
   2. 单页应用：把切换画面的代码放进 document.startViewTransition(() => { … })，React Router 7 的 <Link viewTransition> 就是这样做的；
      多页网站：两个页面都加上 @view-transition { navigation: auto; }；
   3. 时长和缓动写在 ::view-transition-group(这个名字) 上；开启"减少动态"时把这些动画去掉。
   不支持的浏览器直接切换，没有过渡。这种做法本站的动效检查没有覆盖。 */
```

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

```js
// 共享元素过渡（Shared element transition）· 原生 JS，不依赖任何库。
// 做法改写自 Animation Handbook 的 shared-element-transition（MIT License，Copyright (c) 2026 Matin Monshizadeh）：FLIP、默认的时长和缓动、缩小时反算圆角来自它。
// 用法：切换画面之前记下旧元素的框，切换之后调用 sharedElement(旧的框, 新元素)：新元素从旧的框出发，平滑移动、缩放到自己的位置。
//   const first = thumb.getBoundingClientRect(); // 切换前：列表里的缩略图在哪
//   showDetail();                                  // 切换：详情里的大图已经在自己的位置上了
//   sharedElement(first, hero);                    // 大图从缩略图的位置飞过来
// 旧元素还在页面上时，from 也可以直接传元素（这时圆角也按它来）。返回的 Promise 播完是 true，被打断是 false。
// 只动 transform（移动加缩放），不引起重新排版；新元素自己不要再有 transform。缩小时圆角按比例反算，看起来还是原来的圆角。
// 前后长宽比不一样时，图在途中会被拉伸，最好前后同样的比例；新元素要先有确定的大小（比如 aspect-ratio），图片没加载完也量得到终点。
// 飞行途中新元素压在旁边的内容上面（临时加 z-index，播完还原）。
// 同一个元素还没飞完又被调用（比如连点）：先停掉上一次、还原样式，再从新的起点飞。旧的框大小为 0（元素已经删掉或藏起来了）时不做过渡。
// 开启"减少动态"时：不做过渡，新画面直接出现。脚本出错或没执行时：新画面照常显示，只是没有过渡。
// ignoreReducedMotion 只给"用户主动点播放"的演示用，网站自己的过渡不要打开它。
// 单页应用切路由、多页网站跳转时，也可以交给浏览器原生的 View Transitions，见 shared-element.css 里的说明。
const flights = new WeakMap(); // 元素 → 正在飞的那一次

export function sharedElement(from, to, {
  duration = 500,
  easing = 'cubic-bezier(0.2, 0.7, 0.3, 1)',
  ignoreReducedMotion = false,
} = {}) {
  const reduce = !ignoreReducedMotion && matchMedia('(prefers-reduced-motion: reduce)').matches;
  // 先停掉上一次：不然量到的终点是飞行途中的框，样式也会还原错
  flights.get(to)?.stop();
  const a = from instanceof Element ? from.getBoundingClientRect() : from;
  const b = to.getBoundingClientRect();
  if (reduce || !a.width || !a.height || !b.width || !b.height) return Promise.resolve(true);

  const sx = a.width / b.width;
  const sy = a.height / b.height;
  const radius = (el) => parseFloat(getComputedStyle(el).borderTopLeftRadius) || 0;
  const start = from instanceof Element ? radius(from) : radius(to);
  const end = radius(to);
  const anim = to.animate([
    { transformOrigin: '0 0', transform: `translate(${a.left - b.left}px, ${a.top - b.top}px) scale(${sx}, ${sy})`, borderRadius: `${start / sx}px / ${start / sy}px` },
    { transformOrigin: '0 0', transform: 'none', borderRadius: `${end}px` },
  ], { duration, easing });

  // 飞行途中压在旁边的内容上面：没有定位的元素临时加 position: relative（不改变位置），播完还原
  const saved = [to.style.position, to.style.zIndex];
  if (getComputedStyle(to).position === 'static') to.style.position = 'relative';
  to.style.zIndex = '1';
  let landed = false;
  const restore = () => {
    if (landed) return;
    landed = true;
    [to.style.position, to.style.zIndex] = saved;
    if (flights.get(to) === flight) flights.delete(to);
  };
  const flight = { stop: () => { anim.cancel(); restore(); } };
  flights.set(to, flight);
  return anim.finished.then(() => { restore(); return true; }, () => { restore(); return false; });
}
```

## 出处

- Animation Handbook · Shared Element Transition（https://github.com/matinmonshizadeh/animation-handbook/tree/main/animations/03-page-transitions/shared-element-transition，MIT）：改写自它的做法和默认值（FLIP；500ms、cubic-bezier(0.2, 0.7, 0.3, 1)；缩小时反算圆角）；改成原生 JS 的 Web Animations，直接动切换后的元素，不复制；飞行途中压在旁边的内容上面
