Menu icon morph
汉堡菜单变形
Morph a three-line menu icon into a close icon and back.
Also searched as: 三条杠点一下变成叉, 汉堡菜单图标变成关闭图标, 菜单按钮点击变形, 三横线变成 X
- Placement
- Navigation, Button
- Mood
- Crisp, Playful
- Trigger
- 点击
- Site types
- 个人网站, 博客, 作品集
How it works & accessibility
Drive the morph from aria-expanded: the outer bars translate to the center and rotate ±45° while the middle bar scales and fades out, transitioning only transform properties and opacity; clicking toggles state, aria-label and the controlled menu, Escape closes and returns focus, and reduced motion switches instantly.
Best for: Navigation, Button (点击).
Reduced motion: 不播变形,三条杠直接换成叉、叉直接换回三条杠;菜单照常开关
Mobile & touch: 和桌面一样;按钮至少 44×44px 好按
Key parameters
| Parameter | Key | Default | Range | Notes |
|---|---|---|---|---|
| 变形用多久 | duration | 320ms | — | — |
| 两条杠的中心距 | gap | 7px | — | — |
| 缓动 | easing | cubic-bezier(0.4, 0, 0.2, 1) | — | — |
Ready-to-paste AI prompt
Add “Menu icon morph” to the navigation in my project: Drive the morph from aria-expanded: the outer bars translate to the center and rotate ±45° while the middle bar scales and fades out, transitioning only transform properties and opacity; clicking toggles state, aria-label and the controlled menu, Escape closes and returns focus, and reduced motion switches instantly.
Parameters: duration: 320ms, gap: 7px, easing: cubic-bezier(0.4, 0, 0.2, 1).
Preserve existing content and layout. Respect prefers-reduced-motion by showing the final state. Content must remain visible if JavaScript fails or is disabled.
Reference: https://donglang.linter.top/effects/menu-morph.md (canonical specification and reference code).Dependency-free reference code
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; }
}JavaScript
// 汉堡菜单变形(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;
}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>