swipe-to-dismiss滑动关闭
让滑动距离映射到位移与透明度,并在阈值前提供阻尼。
预览
定向拖动越过距离或速度阈值后关闭当前界面元素。
标准减弱
标准减弱
预览
实现「滑动关闭」:让滑动距离映射到位移与透明度,并在阈值前提供阻尼。 参数设为时长 240ms、位移 96px、阻尼 65%、曲线 snap。由真实的指针、触摸或键盘交互触发。使用语义化 HTML,CSS 作用域限定在 .motion-demo--swipe-to-dismiss,并挂载随组件提供的原生 JavaScript 交互运行时。为 prefers-reduced-motion 和 .force-reduced-motion 提供等价的低动态方案。
<div class="motion-demo motion-demo--swipe-to-dismiss" data-motion="swipe-to-dismiss" aria-label="滑动关闭 示例">
<div class="motion-swipe-shell"><article class="motion-surface" tabindex="0" data-swipe-target data-dismiss-label="内容已关闭" aria-label="滑动关闭. 水平滑动关闭;键盘用户按 Delete 键关闭。"><strong>滑动关闭</strong><span class="motion-line"></span><span class="motion-line"></span></article><div class="motion-action-row"><button class="motion-dismiss-button" type="button" data-swipe-dismiss>关闭</button><button class="motion-undo-button" type="button" data-swipe-undo data-restore-label="内容已恢复" hidden>撤销关闭</button></div><span class="motion-status" data-motion-status role="status" aria-live="polite"></span></div>
</div>.motion-demo.motion-demo--swipe-to-dismiss {
box-sizing: border-box;
position: relative;
display: grid;
place-items: center;
width: min(100%, 34rem);
min-height: 15rem;
padding: 2rem;
overflow: hidden;
color: #18181b;
background: #fafafa;
border: 1px solid #e4e4e7;
border-radius: 16px;
isolation: isolate;
}
.motion-demo.motion-demo--swipe-to-dismiss *, .motion-demo.motion-demo--swipe-to-dismiss *::before, .motion-demo.motion-demo--swipe-to-dismiss *::after {
box-sizing: border-box;
}
.motion-demo.motion-demo--swipe-to-dismiss .motion-surface {
position: relative;
display: grid;
gap: 0.65rem;
width: min(100%, 18rem);
padding: 1.25rem;
background: #ffffff;
border: 1px solid #e4e4e7;
border-radius: 16px;
box-shadow: none;
}
.motion-demo.motion-demo--swipe-to-dismiss .motion-surface strong { font-weight: 500; }
.motion-demo.motion-demo--swipe-to-dismiss .motion-line {
display: block;
width: 100%;
height: 0.5rem;
background: #e4e4e7;
border-radius: 999px;
}
.motion-demo.motion-demo--swipe-to-dismiss .motion-line:last-child { width: 62%; }
.motion-demo.motion-demo--swipe-to-dismiss .motion-button {
position: relative;
min-height: 2.75rem;
padding: 0.75rem 1.1rem;
color: white;
font: inherit;
font-weight: 700;
background: #18181b;
border: 0;
border-radius: 999px;
cursor: pointer;
}
.motion-demo.motion-demo--swipe-to-dismiss .motion-button:focus-visible { outline: 3px solid rgb(37 99 235 / 32%); outline-offset: 3px; }
.motion-demo.motion-demo--swipe-to-dismiss .motion-action-row {
display: flex;
justify-content: center;
gap: 0.5rem;
margin-top: 0.85rem;
}
.motion-demo.motion-demo--swipe-to-dismiss .motion-replay-scene {
width: min(100%, 22rem);
display: grid;
place-items: center;
}
.motion-demo.motion-demo--swipe-to-dismiss .motion-pausable-scene {
width: min(100%, 22rem);
display: grid;
place-items: center;
}
.motion-demo.motion-demo--swipe-to-dismiss button.motion-surface {
color: inherit;
font: inherit;
text-align: start;
cursor: pointer;
}
.motion-demo.motion-demo--swipe-to-dismiss .motion-replay-button,
.motion-demo.motion-demo--swipe-to-dismiss .motion-undo-button,
.motion-demo.motion-demo--swipe-to-dismiss .motion-dismiss-button,
.motion-demo.motion-demo--swipe-to-dismiss .motion-pause-button {
min-height: 2.75rem;
padding: 0.65rem 0.9rem;
color: #18181b;
font: 650 0.78rem/1 ui-sans-serif, system-ui, sans-serif;
background: #ffffff;
border: 1px solid #d4d4d8;
border-radius: 8px;
cursor: pointer;
}
.motion-demo.motion-demo--swipe-to-dismiss .motion-replay-button:focus-visible,
.motion-demo.motion-demo--swipe-to-dismiss .motion-undo-button:focus-visible,
.motion-demo.motion-demo--swipe-to-dismiss .motion-dismiss-button:focus-visible,
.motion-demo.motion-demo--swipe-to-dismiss .motion-pause-button:focus-visible,
.motion-demo.motion-demo--swipe-to-dismiss [data-reorder-item]:focus-visible,
.motion-demo.motion-demo--swipe-to-dismiss [data-swipe-target]:focus-visible {
outline: 3px solid rgb(37 99 235 / 32%);
outline-offset: 3px;
}
.motion-demo.motion-demo--swipe-to-dismiss .motion-status {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.motion-demo.motion-demo--swipe-to-dismiss .motion-ripple-ink {
position: absolute;
width: 12px;
height: 12px;
pointer-events: none;
background: rgb(255 255 255 / 72%);
border-radius: 50%;
transform: translate(-50%, -50%) scale(0.95);
opacity: 0;
}
.motion-demo.motion-demo--swipe-to-dismiss .motion-state-stack { position: relative; width: min(100%, 18rem); height: 9rem; }
.motion-demo.motion-demo--swipe-to-dismiss .motion-state { position: absolute; inset: 0; display: grid; place-items: center; padding: 1rem; background: #ffffff; border: 1px solid #e4e4e7; border-radius: 16px; }
.motion-demo.motion-demo--swipe-to-dismiss .motion-state--to { background: #18181b; color: white; }
.motion-demo.motion-demo--swipe-to-dismiss .motion-scroll-track > span { color: #71717a; font: 600 0.72rem/1.2 ui-monospace, monospace; letter-spacing: 0.08em; text-transform: uppercase; }
.motion-demo.motion-demo--swipe-to-dismiss .motion-orbit-item { display: grid; place-items: center; width: 2.5rem; height: 2.5rem; color: white; background: #2563eb; border-radius: 50%; }
.motion-demo.motion-demo--swipe-to-dismiss .motion-text-stack { position: relative; width: min(100%, 18rem); min-height: 4rem; }
.motion-demo.motion-demo--swipe-to-dismiss svg { width: min(100%, 20rem); height: auto; }
.motion-demo.motion-demo--swipe-to-dismiss .motion-swipe-shell { width: min(100%, 18rem); text-align: center; }
.motion-demo.motion-demo--swipe-to-dismiss .motion-surface { width: 100%; touch-action: pan-y; user-select: none; }
.motion-demo.motion-demo--swipe-to-dismiss .motion-surface.is-dragging { cursor: grabbing; }
.motion-demo.motion-demo--swipe-to-dismiss .motion-undo-button[hidden] { display: none; }
@keyframes motion-swipe-to-dismiss-reduced-fade {
from { opacity: 0.84; }
to { opacity: 1; }
}
.force-reduced-motion .motion-demo.motion-demo--swipe-to-dismiss {
animation: motion-swipe-to-dismiss-reduced-fade 160ms cubic-bezier(0.23, 1, 0.32, 1) both !important;
}
.force-reduced-motion .motion-demo.motion-demo--swipe-to-dismiss *,
.force-reduced-motion .motion-demo.motion-demo--swipe-to-dismiss *::before,
.force-reduced-motion .motion-demo.motion-demo--swipe-to-dismiss *::after {
animation: none !important;
animation-delay: 0ms !important;
animation-iteration-count: 1 !important;
transition-property: opacity, color, background-color, border-color !important;
transition-duration: 160ms !important;
transition-delay: 0ms !important;
scroll-behavior: auto !important;
}
.force-reduced-motion .motion-demo.motion-demo--swipe-to-dismiss .motion-button,
.force-reduced-motion .motion-demo.motion-demo--swipe-to-dismiss [data-reorder-item],
.force-reduced-motion .motion-demo.motion-demo--swipe-to-dismiss [data-swipe-target],
.force-reduced-motion .motion-demo.motion-demo--swipe-to-dismiss [data-spring-target] {
transform: none !important;
}
.force-reduced-motion .motion-demo.motion-demo--swipe-to-dismiss .motion-path { stroke-dashoffset: 0 !important; }
.force-reduced-motion .motion-demo.motion-demo--swipe-to-dismiss .motion-word--from { opacity: 0 !important; visibility: hidden; }
.force-reduced-motion .motion-demo.motion-demo--swipe-to-dismiss .motion-word:not(.motion-word--from) { opacity: 1 !important; filter: none !important; transform: none !important; }
@media (prefers-reduced-motion: reduce) {
.motion-demo.motion-demo--swipe-to-dismiss {
animation: motion-swipe-to-dismiss-reduced-fade 160ms cubic-bezier(0.23, 1, 0.32, 1) both !important;
}
.motion-demo.motion-demo--swipe-to-dismiss *, .motion-demo.motion-demo--swipe-to-dismiss *::before, .motion-demo.motion-demo--swipe-to-dismiss *::after {
animation: none !important;
animation-delay: 0ms !important;
animation-iteration-count: 1 !important;
transition-property: opacity, color, background-color, border-color !important;
transition-duration: 160ms !important;
transition-delay: 0ms !important;
scroll-behavior: auto !important;
}
.motion-demo.motion-demo--swipe-to-dismiss .motion-button,
.motion-demo.motion-demo--swipe-to-dismiss [data-reorder-item],
.motion-demo.motion-demo--swipe-to-dismiss [data-swipe-target],
.motion-demo.motion-demo--swipe-to-dismiss [data-spring-target] {
transform: none !important;
}
.motion-demo.motion-demo--swipe-to-dismiss .motion-path { stroke-dashoffset: 0 !important; }
.motion-demo.motion-demo--swipe-to-dismiss .motion-word--from { opacity: 0 !important; visibility: hidden; }
.motion-demo.motion-demo--swipe-to-dismiss .motion-word:not(.motion-word--from) { opacity: 1 !important; filter: none !important; transform: none !important; }
}(() => {
const config = {
"id": "swipe-to-dismiss",
"duration": 240,
"distance": 96,
"resistance": 65,
"position": 50,
"stiffness": 220,
"damping": 24,
"mass": 1,
"velocity": 0,
"rippleSize": 220,
"rippleOpacity": 24,
"dragScale": 103,
"autoplay": false
};
const mount = (root, config) => {
const cleanups = [];
const addCleanup = (callback) => cleanups.push(callback);
const cleanup = () => {
for (let index = cleanups.length - 1; index >= 0; index -= 1) {
try { cleanups[index](); } catch { /* keep cleanup reentrant */ }
}
cleanups.length = 0;
};
const on = (target, type, listener, options) => {
target.addEventListener(type, listener, options);
addCleanup(() => target.removeEventListener(type, listener, options));
};
const reduced = () => root.closest(".force-reduced-motion") !== null ||
window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const watchReduced = (callback) => {
const media = window.matchMedia("(prefers-reduced-motion: reduce)");
const notify = () => callback(reduced());
media.addEventListener("change", notify);
const observer = typeof MutationObserver === "undefined" ? null : new MutationObserver(notify);
let ancestor = root;
while (observer && ancestor) {
observer.observe(ancestor, { attributes: true, attributeFilter: ["class"] });
ancestor = ancestor.parentElement;
}
addCleanup(() => {
media.removeEventListener("change", notify);
if (observer) observer.disconnect();
});
};
const target = root.querySelector("[data-swipe-target]");
const undo = root.querySelector("[data-swipe-undo]");
const dismissButton = root.querySelector("[data-swipe-dismiss]");
const status = root.querySelector("[data-motion-status]");
if (!target || !undo) return cleanup;
const initial = {
status: status ? status.textContent : "",
targetHidden: target.hidden,
undoHidden: undo.hidden,
dismissHidden: dismissButton ? dismissButton.hidden : false,
ariaHidden: target.getAttribute("aria-hidden")
};
let pointerId = null;
let startX = 0;
let startTime = 0;
let rawDistance = 0;
let activeAnimation = null;
const announce = (message) => { if (status) status.textContent = message; };
const clearInline = () => { target.style.transform = ""; target.style.opacity = ""; };
const canonical = () => {
if (activeAnimation) activeAnimation.cancel();
activeAnimation = null;
if (pointerId !== null && target.hasPointerCapture(pointerId)) target.releasePointerCapture(pointerId);
pointerId = null;
rawDistance = 0;
clearInline();
target.classList.remove("is-dragging", "is-dismissed");
target.hidden = initial.targetHidden;
if (initial.ariaHidden === null) target.removeAttribute("aria-hidden");
else target.setAttribute("aria-hidden", initial.ariaHidden);
undo.hidden = initial.undoHidden;
if (dismissButton) dismissButton.hidden = initial.dismissHidden;
if (status) status.textContent = initial.status || "";
};
addCleanup(canonical);
const settle = () => {
const transform = getComputedStyle(target).transform;
const opacity = getComputedStyle(target).opacity;
if (activeAnimation) activeAnimation.cancel();
activeAnimation = target.animate(
reduced()
? [{ opacity }, { opacity: 1 }]
: [{ transform, opacity }, { transform: "translate3d(0, 0, 0)", opacity: 1 }],
{ duration: 180, easing: "cubic-bezier(0.23, 1, 0.32, 1)", fill: "forwards" }
);
activeAnimation.addEventListener("finish", () => { activeAnimation = null; clearInline(); }, { once: true });
};
const dismiss = (direction, keyboard) => {
const finish = () => {
activeAnimation = null;
target.hidden = true;
target.classList.add("is-dismissed");
target.setAttribute("aria-hidden", "true");
if (dismissButton) dismissButton.hidden = true;
undo.hidden = false;
clearInline();
announce(target.dataset.dismissLabel || "Item dismissed");
target.dispatchEvent(new CustomEvent("motion:dismiss", { bubbles: true }));
if (keyboard) undo.focus();
};
if (keyboard) { finish(); return; }
const transform = getComputedStyle(target).transform;
const opacity = getComputedStyle(target).opacity;
const exit = direction * Math.max(root.clientWidth, config.distance * 2);
if (activeAnimation) activeAnimation.cancel();
activeAnimation = target.animate(
reduced()
? [{ opacity }, { opacity: 0 }]
: [{ transform, opacity }, { transform: "translate3d(" + String(exit) + "px, 0, 0)", opacity: 0 }],
{ duration: 200, easing: "cubic-bezier(0.32, 0.72, 0, 1)", fill: "forwards" }
);
activeAnimation.addEventListener("finish", finish, { once: true });
};
const pointerDown = (event) => {
if (!event.isPrimary || event.button !== 0 || pointerId !== null || target.hidden) return;
if (activeAnimation) activeAnimation.cancel();
activeAnimation = null;
pointerId = event.pointerId;
startX = event.clientX;
startTime = performance.now();
rawDistance = 0;
target.setPointerCapture(event.pointerId);
target.classList.add("is-dragging");
};
const pointerMove = (event) => {
if (event.pointerId !== pointerId) return;
rawDistance = event.clientX - startX;
const resistance = Math.min(0.9, Math.max(0.1, config.resistance / 100));
const damped = Math.sign(rawDistance) * Math.pow(Math.abs(rawDistance), 0.9) * (1 - resistance);
const progress = Math.min(1, Math.abs(damped) / Math.max(1, config.distance));
if (!reduced()) target.style.transform = "translate3d(" + String(damped) + "px, 0, 0)";
target.style.opacity = String(1 - progress * 0.5);
};
const pointerUp = (event) => {
if (event.pointerId !== pointerId) return;
if (target.hasPointerCapture(event.pointerId)) target.releasePointerCapture(event.pointerId);
target.classList.remove("is-dragging");
const velocity = Math.abs(rawDistance) / Math.max(1, performance.now() - startTime);
const threshold = Math.min(96, Math.max(48, config.distance * 0.6));
const shouldDismiss = Math.abs(rawDistance) >= threshold || velocity > 0.11;
const direction = rawDistance === 0 ? 1 : Math.sign(rawDistance);
pointerId = null;
if (shouldDismiss) dismiss(direction, false);
else settle();
};
const pointerCancel = (event) => {
if (event.pointerId !== pointerId) return;
if (target.hasPointerCapture(event.pointerId)) target.releasePointerCapture(event.pointerId);
pointerId = null;
target.classList.remove("is-dragging");
settle();
};
const keyDown = (event) => {
if (event.key !== "Delete" && event.key !== "Backspace") return;
event.preventDefault();
dismiss(event.key === "Delete" ? 1 : -1, true);
};
const dismissControl = (event) => dismiss(1, event.detail === 0);
const restore = () => {
if (activeAnimation) activeAnimation.cancel();
target.hidden = false;
target.classList.remove("is-dismissed");
target.removeAttribute("aria-hidden");
undo.hidden = true;
if (dismissButton) dismissButton.hidden = false;
const offset = Math.max(root.clientWidth, config.distance * 2);
activeAnimation = target.animate(
reduced()
? [{ opacity: 0 }, { opacity: 1 }]
: [{ transform: "translate3d(" + String(offset) + "px, 0, 0)", opacity: 0 }, { transform: "translate3d(0, 0, 0)", opacity: 1 }],
{ duration: reduced() ? 160 : 200, easing: "cubic-bezier(0.32, 0.72, 0, 1)" }
);
announce(undo.dataset.restoreLabel || "Item restored");
target.focus();
};
on(target, "pointerdown", pointerDown);
on(target, "pointermove", pointerMove);
on(target, "pointerup", pointerUp);
on(target, "pointercancel", pointerCancel);
on(target, "keydown", keyDown);
if (dismissButton) on(dismissButton, "click", dismissControl);
on(undo, "click", restore);
return cleanup;
};
document.querySelectorAll("[data-motion=\"swipe-to-dismiss\"]").forEach((root) => {
const cleanupKey = "__motionLexiconCleanup";
if (typeof root[cleanupKey] === "function") root[cleanupKey]();
root[cleanupKey] = mount(root, config);
});
})();深入了解
术语与辨析
swipe-to-dismiss滑动关闭
Swipe to dismiss英文定义
A directional drag removes a surface after distance or velocity crosses a dismissal threshold.
中文翻译
定向拖动越过距离或速度阈值后关闭当前界面元素。
rubber-banding橡皮筋回弹
Rubber-banding英文定义
Movement beyond a boundary is attenuated, then restored toward the valid range after release.
中文翻译
拖过边界时出现阻力并回弹,类似 iOS 的过度滚动手感。
辨析
橡皮筋回弹发生在拖过边界后,并带阻力返回;滑动关闭以越过阈值后移除元素为目标。
实现前检查
- 目的
- 把滑动距离映射到位移和透明度,让用户可预判关闭结果。
- 频率
- 适合中频通知、抽屉或单项操作;核心信息必须提供按钮替代。
- 触发
- 由水平或垂直拖拽超过启动阈值触发,并先锁定主轴。
- 进入 / 离开
- 阈值前使用阻尼跟手,越过阈值后离场;未达到阈值则回弹原位。
- 可打断性
- 反向拖动立即改变进度;pointercancel 使用当前位置决定回弹。
- 手势与键盘
- 避免与页面滚动轴冲突,设置 touch-action,并提供撤销或显式关闭按钮。
- 减弱动效策略
- 使用静态关闭按钮与即时移除,保留撤销反馈;取消大幅滑出。
可访问性
减弱动效
使用静态关闭按钮与即时移除,保留撤销反馈;取消大幅滑出。
参数参考
| 参数 | 范围 / 选项 | 默认值 | 作用 |
|---|---|---|---|
duration | 80ms–1200ms | 240ms | 控制一次动效完成所需的时间。 |
distance | 0px–240px | 96px | 控制元素移动的空间距离。 |
resistance | 0%–90% | 65% | 调节阻尼。 |
ease | 柔和 / 清脆 / 平稳 / 匀速 | 清脆 | 控制速度随时间变化的方式。 |
交付前检查
- 区分滑动关闭与橡皮筋回弹的交互目标。
- 测试慢拖、快甩、短距离和取消路径。