# 汉堡菜单变形（Menu icon morph）

- 俗称：三条杠点一下变成叉；汉堡菜单图标变成关闭图标；菜单按钮点击变形；三横线变成 X
- 用在：导航、按钮（个人网站、博客、作品集）
- 触发：点击
- 感觉：利落、俏皮
- 版本：1，更新于 2026-11-05

## 原理

按钮的状态写在 aria-expanded 上，CSS 按它变形：上下两条杠用 translate 挪到中间、rotate 转 ±45°，中间那条用 scale 和透明度缩没；每条杠只过渡位移、旋转、透明度、缩放；点按钮（键盘空格、回车也算）切换状态、改 aria-label、显示或藏起被控制的菜单，Esc 关上并把焦点还给按钮；减少动态时直接变，不过渡。

适合：手机上的导航菜单按钮、侧栏的开关：点一下图标从"三条杠"变成"叉"，告诉人"现在点它是关掉"，比一下子换图标顺。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `duration` | 变形用多久 | 320ms | 150–700ms |
| `gap` | 两条杠的中心距 | 7px | 4–12px |
| `easing` | 缓动 | cubic-bezier(0.4, 0, 0.2, 1) | — |

## 质量要求

- 开启"减少动态"时：不播变形，三条杠直接换成叉、叉直接换回三条杠；菜单照常开关。
- 手机上：和桌面一样；按钮至少 44×44px 好按。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

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

```text
请在我的项目里给导航加上「汉堡菜单变形」（Menu icon morph）效果：按钮的状态写在 aria-expanded 上，CSS 按它变形：上下两条杠用 translate 挪到中间、rotate 转 ±45°，中间那条用 scale 和透明度缩没；每条杠只过渡位移、旋转、透明度、缩放；点按钮（键盘空格、回车也算）切换状态、改 aria-label、显示或藏起被控制的菜单，Esc 关上并把焦点还给按钮；减少动态时直接变，不过渡。
参数：变形用多久 320ms，两条杠的中心距 7px，缓动 cubic-bezier(0.4, 0, 0.2, 1)。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/menu-morph.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<!-- 汉堡菜单变形：按钮的状态写在 aria-expanded 上，三条杠是装饰；aria-controls 指向被控制的菜单（菜单里不写 hidden：没有脚本时链接照样看得见，脚本装上、当前是关着的才给它加 hidden） -->
<button class="mm-btn" type="button" aria-expanded="false" aria-controls="menu" aria-label="打开菜单"><i></i><i></i><i></i></button>
<nav id="menu">
  <a href="/">首页</a>
  <a href="/posts/">文章</a>
  <a href="/about/">关于</a>
</nav>
<script type="module">
  import { menuMorph } from './menu-morph.js';
  const button = document.querySelector('.mm-btn');
  menuMorph(button, { duration: 320, gap: 7, easing: 'cubic-bezier(0.4, 0, 0.2, 1)' });
  button.addEventListener('menutoggle', (e) => console.log(e.detail.open ? '菜单打开了' : '菜单关上了'));
</script>
```

CSS：

```css
/* 汉堡菜单变形的样式，配合 menu-morph.js。状态在按钮的 aria-expanded 上：true 时上下两条杠挪到中间、转 ±45°，中间那条缩没（变成叉）。
   每条杠只过渡位移、旋转、透明度、缩放；时长、中心距、缓动是 --mm-duration、--mm-gap、--mm-easing（脚本按选项写在按钮的行内）。
   按钮至少 44×44px 好按。开启"减少动态"时直接变、不过渡（演示强制播放时按钮有 data-mm-motion，就不关）。 */
/* 变量的默认值写在 :where() 里（不占优先级）：网站自己在 .mm-btn 上改的，不管写在这段代码前面还是后面，都用网站自己的
   （装上脚本以后，脚本按选项把它们写在按钮的行内样式上） */
:where(.mm-btn) {
  --mm-duration: 320ms;
  --mm-gap: 7px;
  --mm-easing: cubic-bezier(0.4, 0, 0.2, 1);
}
.mm-btn {
  display: inline-grid;
  place-content: center;
  gap: calc(var(--mm-gap) - 2px);
  min-width: 44px;
  min-height: 44px;
}
.mm-btn > i {
  display: block;
  width: 22px;
  height: 2px;
  border-radius: 2px;
  background: currentColor;
  transition: translate var(--mm-duration) var(--mm-easing), rotate var(--mm-duration) var(--mm-easing), opacity var(--mm-duration) var(--mm-easing), scale var(--mm-duration) var(--mm-easing);
}
.mm-btn[aria-expanded="true"] > i:nth-child(1) {
  translate: 0 var(--mm-gap);
  rotate: 45deg;
}
.mm-btn[aria-expanded="true"] > i:nth-child(2) {
  opacity: 0;
  scale: 0 1;
}
.mm-btn[aria-expanded="true"] > i:nth-child(3) {
  translate: 0 calc(var(--mm-gap) * -1);
  rotate: -45deg;
}
@media (prefers-reduced-motion: reduce) {
  .mm-btn:not([data-mm-motion]) > i { transition: none; }
}
```

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

```js
// 汉堡菜单变形（Menu icon morph）· 原生 JS，不依赖任何库。
// 参考 StyleKit 的 morph-shape、Motion Lexicon 的 morph 的做法（都是 MIT），自己实现，没有复制代码；只做菜单图标这一种变形（位移和旋转，不改路径）。
// 结构：<button class="mm-btn" type="button" aria-expanded="false" aria-controls="menu" aria-label="打开菜单"><i></i><i></i><i></i></button>
// 加一个被控制的 <nav id="menu">（不写 hidden：没有脚本时链接照样看得见，脚本装上、当前是关着的才加 hidden；配合 menu-morph.css）。三条杠是装饰，状态写在按钮的 aria-expanded 上，CSS 按它变形。
// 用法：menuMorph(按钮)，返回 { open(), close(), toggle(), isOpen, destroy() }。点按钮（键盘空格、回车也会触发 click）切换：
// 改 aria-expanded、aria-label（"打开菜单"/"关闭菜单"，选项 labels: { open, close } 换语言），切 aria-controls 指的元素的 hidden，
// 状态都改好以后在按钮上发 CustomEvent('menutoggle', { detail: { open } })。open()、close() 已经是那个状态时什么都不做。
// Esc 在菜单打开时关上它，并把焦点还给按钮（监听挂在 document 上，只在打开时有）。
// 选项：duration 变形用多久（毫秒）、gap 两条杠的中心距（px）、easing 缓动，写在按钮行内的 --mm-duration、--mm-gap、--mm-easing 上（destroy() 时清掉）。
// 开启"减少动态"时直接变，不过渡（menu-morph.css 里关掉；ignoreReducedMotion 只给演示强制播放用，它给按钮加 data-mm-motion）。
// 没有脚本时：被控制的菜单在 HTML 里不写 hidden，链接照样看得见（装上脚本、当前是关着的，才给它加 hidden）；
// 不想让菜单在脚本装上前闪一下的话，自己用 CSS 在装上前先藏起来，同时给没有脚本的情况留一条出路（比如 <noscript> 里放一份展开的菜单）。
// 杠高 2px（CSS 里写死），中心距才等于 gap；改杠高要同时改 CSS 里的 gap 算式。
// destroy()：摘掉按钮的 click 和 document 的 keydown 监听、清行内变量；之后点按钮不再变（按钮的 aria-expanded、菜单的 hidden 停在当时的状态，交还给页面）；
// 对同一个按钮重复调用先拆旧的。

// 每个按钮现在装着的控制对象（对同一个按钮重复调用时先拆旧的）
const prevs = new WeakMap();

export function menuMorph(button, {
  duration = 320,
  gap = 7,
  easing = 'cubic-bezier(0.4, 0, 0.2, 1)',
  labels = {},
  ignoreReducedMotion = false,
} = {}) {
  prevs.get(button)?.destroy();
  const text = { open: labels.open ?? '打开菜单', close: labels.close ?? '关闭菜单' };
  button.style.setProperty('--mm-duration', `${duration}ms`);
  button.style.setProperty('--mm-gap', `${gap}px`);
  button.style.setProperty('--mm-easing', easing);
  if (ignoreReducedMotion) button.setAttribute('data-mm-motion', '');
  let open = button.getAttribute('aria-expanded') === 'true';
  let dead = false;

  const sync = () => {
    button.setAttribute('aria-expanded', String(open));
    button.setAttribute('aria-label', open ? text.close : text.open);
    const id = button.getAttribute('aria-controls');
    const menu = id ? document.getElementById(id) : null;
    if (menu) menu.hidden = !open;
  };
  const onKeyDown = (e) => {
    if (e.key !== 'Escape' || !open) return;
    set(false, true);
  };
  // refocus：Esc 关上时把焦点还给按钮——先还焦点、再发事件（页面监听 menutoggle 时看到的是最终状态）。
  // 藏起菜单、挪焦点都会同步触发页面的 focus/blur 回调，里面可能 destroy()，也可能又调 open()、toggle()：
  // 每一步以后重新看一眼——销毁了、或者状态已经被回调改走了（那一次自己已经挂好监听、发过事件），外面这次就不做了
  const set = (next, refocus = false) => {
    if (dead || next === open) return;
    open = next;
    sync();
    if (dead || open !== next) return;
    if (open) document.addEventListener('keydown', onKeyDown);
    else document.removeEventListener('keydown', onKeyDown);
    if (refocus) button.focus({ preventScroll: true });
    if (dead || open !== next) return;
    button.dispatchEvent(new CustomEvent('menutoggle', { detail: { open } }));
  };
  const onClick = () => set(!open);
  button.addEventListener('click', onClick);
  if (open) document.addEventListener('keydown', onKeyDown);
  sync();

  const ctl = {
    get isOpen() { return open; },
    open() { set(true); },
    close() { set(false); },
    toggle() { set(!open); },
    destroy() {
      if (dead) return;
      dead = true;
      button.removeEventListener('click', onClick);
      document.removeEventListener('keydown', onKeyDown);
      button.style.removeProperty('--mm-duration');
      button.style.removeProperty('--mm-gap');
      button.style.removeProperty('--mm-easing');
      button.removeAttribute('data-mm-motion');
      if (prevs.get(button) === ctl) prevs.delete(button);
    },
  };
  prevs.set(button, ctl);
  return ctl;
}
```

## 出处

- 参考 StyleKit morph-shape、Motion Lexicon morph 的做法（图标从一种形状变到另一种），自己实现，没有复制代码；只做了菜单图标这一种变形，用位移和旋转、不改路径；状态写在 aria-expanded、Esc 关上还焦点、减少动态直接变是本站自己定的
