侧边滑入滑出
Slide in / out
点一下菜单,侧栏从屏幕边上滑进来,再点一下滑回去
常见大白话搜法:侧边栏从边上滑出来、抽屉菜单滑入滑出、菜单从左边滑进来、面板从屏幕边缘滑出来
- 适用位置
- 导航、页面切换
- 气质感觉
- 利落、柔和
- 触发方式
- 点击
- 适合网站
- 个人网站、博客、工具站
实现原理与无障碍底线
侧栏平时用 translate 推到屏幕外、加 inert(Tab 不到、读屏读不到);打开时去掉 inert、translate 过渡回 0,焦点移进侧栏,关上时还给原来的按钮;Esc 也能关;只过渡 translate 一个属性;减少动态时直接到位;没有脚本时侧栏就是页面里一块普通内容。
适用场景:手机上的导航菜单、博客的目录、工具站的设置面板:平时收在屏幕外,点一下汉堡图标滑进来,用完滑回去,不挡页面别的地方
减少动态(prefers-reduced-motion):不播滑动,侧栏直接出现、直接收起;焦点和 Esc 照常
移动端与触屏:和桌面一样;侧栏宽度是 min(320px, 85vw),手机上留一条边看得见页面
关键可调参数
| 参数 | 键名 | 默认值 | 建议范围 | 说明 |
|---|---|---|---|---|
| 滑动时长 | duration | 320ms | — | — |
| 缓动 | easing | cubic-bezier(0.32, 0.72, 0, 1) | — | — |
可直接复制给 AI(Cursor / Claude / v0)的提示词
请在我的项目里给导航加上「侧边滑入滑出」(Slide in / out)效果:侧栏平时用 translate 推到屏幕外、加 inert(Tab 不到、读屏读不到);打开时去掉 inert、translate 过渡回 0,焦点移进侧栏,关上时还给原来的按钮;Esc 也能关;只过渡 translate 一个属性;减少动态时直接到位;没有脚本时侧栏就是页面里一块普通内容。
参数:滑动时长 320ms,缓动 cubic-bezier(0.32, 0.72, 0, 1)。
要求:保留原有的内容和布局;系统开启"减少动态"时直接显示最终状态;脚本出错或没有执行时内容仍然可见。
参考:https://donglang.linter.top/effects/slide-panel.md(原理、参数和参考代码)原生无依赖参考代码
CSS
/* 侧边滑入滑出的样式,配合 slide-panel.js。只有脚本装好以后([data-sp-ready])才把侧栏变成固定在屏幕边上的抽屉;
没有脚本时侧栏就是页面里一块普通内容。只过渡 translate 一个属性(时长、缓动来自脚本写的 --sp-duration、--sp-easing)。
开启"减少动态"时不过渡(直接到位);脚本的 ignoreReducedMotion(演示强制播放)给侧栏加 data-sp-motion,有它就不关。 */
.sp-panel[data-sp-ready] {
position: fixed;
top: 0;
bottom: 0;
left: 0;
z-index: 50;
width: min(320px, 85vw);
overflow: auto;
transition: translate var(--sp-duration, 320ms) var(--sp-easing, cubic-bezier(0.32, 0.72, 0, 1));
}
.sp-panel[data-sp-ready][data-side="right"] {
left: auto;
right: 0;
}
/* 关着:推到屏幕外(左边的往左推一个自身宽度,右边的往右推) */
.sp-panel[data-sp-ready][data-open="false"] {
translate: -100% 0;
}
.sp-panel[data-sp-ready][data-side="right"][data-open="false"] {
translate: 100% 0;
}
@media (prefers-reduced-motion: reduce) {
.sp-panel[data-sp-ready]:not([data-sp-motion]) { transition: none; }
}JavaScript
// 侧边滑入滑出(Slide in / out)· 原生 JS,不依赖任何库。
// 参考 StyleKit 的 slide-in-left / slide-in-right / slide-out-right、Animation Handbook 的 slide-in、Motion Lexicon 的 slide-in 的做法(都是 MIT),自己实现,没有复制代码。
// panel 是一个侧栏,比如 <aside class="sp-panel" id="drawer" aria-label="菜单">…</aside>(配合 slide-panel.css)。
// 返回 { open(), close(), toggle(), isOpen, destroy() }:打开按钮上写 button.addEventListener('click', () => ctl.toggle()),
// 按钮自己的 aria-expanded 由页面在 panelchange 事件里改(这个文件不管按钮)。
// 非模态:没有遮罩、不锁焦点,页面其余地方照常能操作。Esc 挂在 document 上(只在打开时有)、不 preventDefault,页面上别的 Esc 处理照常触发。
// 样式只管位置和滑动:背景色、字色、阴影由页面自己写在侧栏上(不写的话侧栏是透明的,叠在正文上看不清)。
// 没有脚本时侧栏就是页面里一块普通内容(slide-panel.css 只有在 [data-sp-ready] 之下才把它变成固定在屏幕边上的抽屉)。
// 装上以后一开始是关着的(侧栏带 data-open="true" 的话是开着的):关着 = 推到屏幕外(translate: -100% 0,右边是 100% 0)并且 inert
// (Tab 不到、读屏读不到);开着 = translate: 0 0、没有 inert。位移用一个 CSS 过渡,只过渡 translate 一个属性;
// 时长、缓动写在侧栏行内的 --sp-duration、--sp-easing 上(destroy() 时清掉);过渡中途又开又关,CSS 过渡自己从当时的位置掉头。
// open():记下现在有焦点的元素,去掉 inert,把焦点移进侧栏(第一个能聚焦的元素;没有就聚焦侧栏自己,这时给它加 tabindex="-1")。
// close():加 inert,焦点还在侧栏里(或者落在 body 上)时还给打开前的那个元素(它还在页面上的话);焦点已经被用户挪到页面别处时不抢回来。
// Esc 在侧栏打开时关上它(监听挂在 document 上,只在打开时有)。状态都改好以后,在侧栏上发 CustomEvent('panelchange', { detail: { open } })。
// side:'left'(默认)或 'right',侧栏从哪一边出来。duration 是毫秒、easing 是 CSS 缓动,和数据里一样。
// moveFocus:默认 true;页面自己管焦点(或者只是展示用、不该抢走页面焦点)时传 false,打开时不移动焦点。
// 开启"减少动态"时位移直接到位,不过渡(slide-panel.css 里关掉;ignoreReducedMotion 只给演示强制播放用,它给侧栏加 data-sp-motion)。
// destroy():摘监听、清行内变量,去掉加上的 data-sp-ready、data-side、data-open、data-sp-motion、inert、tabindex(恢复成加之前的样子),
// 之后 open/close/toggle 什么都不做;对同一个侧栏重复调用 slidePanel,先 destroy 旧的。
// 每个侧栏现在装着的控制对象(对同一个侧栏重复调用时先拆旧的)
const prevs = new WeakMap();
const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
export function slidePanel(panel, {
side = 'left',
duration = 320,
easing = 'cubic-bezier(0.32, 0.72, 0, 1)',
moveFocus = true,
ignoreReducedMotion = false,
} = {}) {
prevs.get(panel)?.destroy();
// 装之前的样子:destroy() 照这个恢复(页面自己写的属性不动)
const before = {};
for (const name of ['data-sp-ready', 'data-side', 'data-open', 'data-sp-motion', 'inert', 'tabindex']) before[name] = panel.getAttribute(name);
let open = panel.getAttribute('data-open') === 'true';
let destroyed = false;
let returnTo = null;
panel.style.setProperty('--sp-duration', `${duration}ms`);
panel.style.setProperty('--sp-easing', easing);
panel.setAttribute('data-side', side === 'right' ? 'right' : 'left');
if (ignoreReducedMotion) panel.setAttribute('data-sp-motion', '');
panel.setAttribute('data-open', open ? 'true' : 'false');
if (open) panel.removeAttribute('inert'); else panel.setAttribute('inert', '');
// 最后才加 data-sp-ready:这一刻 CSS 才把它变成抽屉。加的那一下临时关掉过渡(强制回流再还原),
// 不然 translate 从"没有"变成"推到屏幕外"也会播一次过渡:页面一打开侧栏先露一下再滑走
const inlineTransition = panel.style.transition;
panel.style.transition = 'none';
panel.setAttribute('data-sp-ready', '');
void panel.offsetWidth;
panel.style.transition = inlineTransition;
const onKeyDown = (e) => { if (e.key === 'Escape' && open) ctl.close(); };
const announce = () => panel.dispatchEvent(new CustomEvent('panelchange', { detail: { open } }));
if (open) document.addEventListener('keydown', onKeyDown);
const ctl = {
get isOpen() { return open; },
open() {
if (destroyed || open) return;
open = true;
returnTo = document.activeElement instanceof HTMLElement && !panel.contains(document.activeElement) ? document.activeElement : null;
panel.removeAttribute('inert');
panel.setAttribute('data-open', 'true');
document.addEventListener('keydown', onKeyDown);
if (moveFocus) {
const first = panel.querySelector(FOCUSABLE);
if (first) first.focus({ preventScroll: true });
else {
if (!panel.hasAttribute('tabindex')) panel.setAttribute('tabindex', '-1');
panel.focus({ preventScroll: true });
}
}
if (destroyed) return; // 挪焦点会同步触发页面的 focus/blur 回调,里面可能 destroy():销毁了就不再发事件
announce();
},
close() {
if (destroyed || !open) return;
open = false;
document.removeEventListener('keydown', onKeyDown);
// 焦点在侧栏里(或者已经掉到 body 上)才还回去:加 inert 以后侧栏里的焦点会掉到 body,先记下来
const active = document.activeElement;
const inside = active === document.body || panel.contains(active);
panel.setAttribute('data-open', 'false');
panel.setAttribute('inert', '');
if (destroyed) return; // 加 inert 会让里面的焦点掉出去,同步触发页面的 blur 回调,里面可能 destroy()
if (inside && returnTo && returnTo.isConnected) returnTo.focus({ preventScroll: true });
returnTo = null;
if (destroyed) return; // 还焦点同样会触发页面的回调
announce();
},
toggle() { if (open) ctl.close(); else ctl.open(); },
destroy() {
if (destroyed) return;
destroyed = true;
document.removeEventListener('keydown', onKeyDown);
panel.style.removeProperty('--sp-duration');
panel.style.removeProperty('--sp-easing');
for (const [name, value] of Object.entries(before)) {
if (value === null) panel.removeAttribute(name); else panel.setAttribute(name, value);
}
if (prevs.get(panel) === ctl) prevs.delete(panel);
},
};
prevs.set(panel, ctl);
return ctl;
}HTML
<!-- 侧边滑入滑出:一个打开按钮,一个侧栏(aside)。没有脚本时侧栏就是页面里一块普通内容 -->
<!-- 按钮的 aria-expanded、aria-controls 由页面自己管(在 panelchange 事件里改),脚本只管侧栏 -->
<button type="button" id="menu-button" aria-expanded="false" aria-controls="drawer">菜单</button>
<aside class="sp-panel" id="drawer" aria-label="菜单">
<nav>
<a href="/">首页</a>
<a href="/posts/">文章</a>
<a href="/about/">关于</a>
</nav>
<button type="button" id="drawer-close">关闭</button>
</aside>
<script type="module">
import { slidePanel } from './slide-panel.js';
const drawer = document.getElementById('drawer');
const button = document.getElementById('menu-button');
const panel = slidePanel(drawer, { side: 'left', duration: 320, easing: 'cubic-bezier(0.32, 0.72, 0, 1)' });
button.addEventListener('click', () => panel.toggle());
document.getElementById('drawer-close').addEventListener('click', () => panel.close());
drawer.addEventListener('panelchange', (e) => button.setAttribute('aria-expanded', String(e.detail.open)));
</script>