通知按住往左滑删掉
- 9:02 收到一条新留言
- 10:15 订阅的周刊到了
- 11:40 服务器备份完成
- 12:00 有人收藏了你的站点
滑走移除
Swipe to dismiss
按住一条往旁边滑,越滑越淡,过了线就飞走、下面的补上来
常见大白话搜法:往旁边一滑就删掉这一条、左滑删除、手机上滑走通知、划掉列表项
- 适用位置
- 卡片列表
- 气质感觉
- 利落、俏皮
- 触发方式
- 点击
- 适合网站
- 个人网站、工具站
实现原理与无障碍底线
整项跟手指横着走(translate,不加过渡)、透明度跟着滑的比例降(滑满一个项宽时降到 0.4,最多降 0.6);松手时过了项宽的四成(或最后甩得够快)就往滑的方向飞出去(飞到项宽再加 40px 的地方、透明度到 0)、把高度收成 0 再从页面里拿掉,没过线就过渡回原位;项上用 touch-action: pan-y 只把横向手势留给自己,竖着照常滚页面;键盘 Delete 也能移除,读屏有提示。
适用场景:手机上的通知、邮件、待办列表:一条条处理掉的地方
减少动态(prefers-reduced-motion):跟手照常(那是直接操作),飞出去、收高度、弹回不用过渡,直接到位;顺序和事件照常
移动端与触屏:只在项上关掉竖向以外的触摸手势(touch-action: pan-y),竖着滚页面照常
关键可调参数
| 参数 | 键名 | 默认值 | 建议范围 | 说明 |
|---|---|---|---|---|
| 滑过几成算移除 | threshold | 40% | — | — |
| 飞出去和弹回的时长 | duration | 260ms | — | — |
| 缓动 | easing | cubic-bezier(0.2, 0, 0, 1) | — | — |
可直接复制给 AI(Cursor / Claude / v0)的提示词
请在我的项目里给卡片列表加上「滑走移除」(Swipe to dismiss)效果:整项跟手指横着走(translate,不加过渡)、透明度跟着滑的比例降(滑满一个项宽时降到 0.4,最多降 0.6);松手时过了项宽的四成(或最后甩得够快)就往滑的方向飞出去(飞到项宽再加 40px 的地方、透明度到 0)、把高度收成 0 再从页面里拿掉,没过线就过渡回原位;项上用 touch-action: pan-y 只把横向手势留给自己,竖着照常滚页面;键盘 Delete 也能移除,读屏有提示。
参数:滑过几成算移除 40%,飞出去和弹回的时长 260ms,缓动 cubic-bezier(0.2, 0, 0, 1)。
要求:保留原有的内容和布局;系统开启"减少动态"时直接显示最终状态;脚本出错或没有执行时内容仍然可见。
参考:https://donglang.linter.top/effects/swipe-dismiss.md(原理、参数和参考代码)原生无依赖参考代码
CSS
/* 滑走移除(Swipe to dismiss)的样式,配合 swipe-dismiss.js。脚本给正在滑的那一项加 class="is-swiping",
按参数设置 --sd-duration、--sd-easing;飞出去/弹回/收高度的过渡由脚本写在项的行内样式里(滑着的那一项除外:它跟指针走,不过渡)。
开启"减少动态"时飞出去、收高度、弹回不用过渡(直接到位),顺序和事件照常。 */
.sd-live {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
clip-path: inset(50%);
overflow: hidden;
white-space: nowrap;
}
/* 项:touch-action 只留竖向(竖着滚页面照常,横着归手势) */
.sd-list > li {
touch-action: pan-y;
}
/* position 让拿起时的 z-index 生效;用 :where() 把优先级降到 0——页面自己给项写了 sticky、absolute 的,用页面的 */
:where(.sd-list > li) {
position: relative;
}
/* 正在滑的那一项:去掉过渡(跟指针走),盖在邻居上面,滑的时候文字不被选中 */
.sd-list > .is-swiping {
z-index: 1;
transition: none;
box-shadow: var(--sd-shadow, 0 14px 28px -12px rgb(0 0 0 / 0.4));
user-select: none;
-webkit-user-select: none;
}JavaScript
// 滑走移除(Swipe to dismiss)· 原生 JS,不依赖任何库。
// 参考 Animation Handbook 的 swipe-to-dismiss、Motion Lexicon 的 swipe-to-dismiss(两者都是 MIT)的做法,自己实现,没有复制代码:
// 按住一项往左或往右滑,这一项跟着手横着走、越滑越淡;松手时过了线(滑过项宽的 threshold 成)或最后甩得够快,就朝滑的方向
// 飞出去、把高度收成 0、从页面里拿掉,剩下的项补上来;没过线就过渡回原位。
// list 是一个列表(配合 swipe-dismiss.css,给列表加上 class="sd-list"),它的每个子元素是一项(<li>),整项就是手势的区域
// (没有手柄);项上加 tabindex="0"(键盘的 Delete/Backspace 要用)。没有脚本时它就是一个普通列表,内容不变。
// 按下的地方是 a、button、input、textarea、select 或 [data-no-swipe] 里面:忽略(不抢项里的按钮和链接)。
// 触摸和鼠标都走 Pointer Events(监听在 list 上,pointerdown 认项)。浏览器自己的触摸手势:项上写 touch-action: pan-y
// (竖着滚页面照常,横着归我们)。按下后先不动:横向位移超过 6px 且 |dx| > |dy| 才认定是横滑(这时才 setPointerCapture、
// 算"拿起",同时清掉鼠标已经拖出来的文字选区);dy 比 dx 大就当竖滚,放弃,什么都不改。
// 键盘(项 tabindex="0",Tab 能到):焦点在项上按 Delete 或 Backspace 移除(向左飞出去,和手势走同一个"移除");
// 移除以后焦点给下一项(没有下一项给上一项,都没有就不动)。这是手势的键盘替代(WCAG 2.2 的 2.5.7)。
// 读屏提示写在 list 后面一个 aria-live="polite"、视觉上隐藏的元素里(destroy() 时移除)。提示的句子可以用 messages 选项
// 换语言(removed(name, left)、cancelled() 两个函数),不传就是中文;removed 的 left 是"这一项移除以后列表里还剩几个"。
// 相同的句子连续两次也要能念:句尾交替加零宽空格(写成 "\u200b" 转义)。
// 移除:先飞出去(translate 到 ±(项宽 + 40px)、透明度到 0,duration、easing 过渡),再把高度收成 0(height、margin、padding
// 过渡到 0,时长是 duration 的 80%,overflow: hidden;收高度时项临时是 box-sizing: border-box、上下边框一开始就去掉,高度不会先跳一下、
// 拿掉的那一刻后面的项也不会多跳一个边框的宽度),
// 收完把这一项从 DOM 里拿掉,最后在 list 上发 CustomEvent('dismiss', { detail: { item, index, direction } })
// (index 是拿掉之前在列表里的下标,从 0 起;direction 是 'left' 或 'right';item 是被拿掉的元素本身,行内样式是干净的,
// 页面要撤销可以直接放回原来的位置)。弹回:translate 过渡回 0、透明度回 1(duration、easing)。
// pointercancel、失去捕获:弹回,不移除,不发事件。
// 返回 { grab(item, x, y), move(x, y), drop(), cancel(), dismiss(item, direction), destroy() }(演示、检查用;手势和键盘内部也走这几个)。
// x、y 是指针相对 list 左上角的位置。速度从"松手前最近 80ms 内 move 调用的时间和位置"算(performance.now())。
// 松手算不算移除:|dx| ≥ threshold × 项宽,或者最近 80ms 的速度 ≥ 0.5 px/ms(朝着滑的方向)且 |dx| ≥ 40px。
// 全库同时只有一项被拿起;键盘正在操作某一项时指针先取消;第二根手指的按下被忽略。
// 松手以后同一时间只有一件事在走(弹回、飞出去、收高度):开始新的一件(grab()、dismiss()、drop())之前,先把没走完的这一件
// 提交(弹回的回到原位;移除的拿掉并发 dismiss);cancel() 和 destroy() 是中止(清定时器、摘 transitionend 监听、清样式),
// 不改顺序、不发事件。接住还在弹回的项时,它从原位重新开始跟手。
// 开启"减少动态"时:跟手照常(那是直接操作,不是装饰),但飞出去、收高度、弹回不用过渡,直接到位——
// dismiss() 返回之前项已经拿掉、事件已经发了;顺序和事件照常;选项 ignoreReducedMotion 只给演示强制播放用。
// 只支持竖排列表(项在上下方向排开)。项宽为 0 时不拿起,也不触发任何事。列表被外部增删项不处理,要改列表先 destroy()。
// 项之间的间距请写成项自己的 margin-bottom,不要用 flex/grid 的 gap:收高度收的是项自己的外边距,gap 要到项拿掉的那一刻才消失,后面的项会跳一下。
// threshold 在 options 里写百分数(40 就是 40%,和数据里 % 同一个数),不是 0.4——这是全站的规矩:数据里写 %,options 里就写百分数。
// 每个列表现在装着的控制对象(对同一个列表重复调用时先拆旧的)
const prevs = new WeakMap();
export function swipeDismiss(list, {
threshold = 40,
duration = 260,
easing = 'cubic-bezier(0.2, 0, 0, 1)',
ignoreReducedMotion = false,
messages = {},
} = {}) {
prevs.get(list)?.destroy();
// duration、easing 写进列表的 CSS 变量:飞出去/弹回(行内过渡)和收高度(行内过渡)都用它们
list.style.setProperty('--sd-duration', `${duration}ms`);
list.style.setProperty('--sd-easing', easing);
const reduce = () => !ignoreReducedMotion && matchMedia('(prefers-reduced-motion: reduce)').matches;
const items = () => [...list.children].filter((el) => el instanceof HTMLElement);
// 项的名字:textContent 拍扁空白
const nameOf = (item) => (item.textContent || '').trim().replace(/\s+/g, ' ');
// 读屏提示:默认中文,句子用 messages 选项换语言(相同的句子连续两次的处理见下面的 say)
const sayings = {
removed: messages.removed ?? ((name, left) => `已移除:${name},还剩 ${left} 个`),
cancelled: messages.cancelled ?? (() => '已取消'),
};
// 读屏提示
const live = document.createElement('div');
live.setAttribute('aria-live', 'polite');
live.setAttribute('aria-atomic', 'true'); // 每次整句替换,读屏要整句念,不是只念变了的几个字
live.className = 'sd-live';
list.after(live);
// 念一句:自己的活区还在文档里就写自己的;页面在 dismiss 回调里重新渲染(destroy 旧的、装新的)以后,旧的活区已经拿掉了,
// 改写紧跟在列表后面的那个新活区,提示不丢。同一句连续念两次:和活区里现在的字一样时在句尾加一个零宽空格,字不一样读屏才会再念
const say = (text) => {
const target = live.isConnected ? live : (list.nextElementSibling?.matches('.sd-live') ? list.nextElementSibling : null);
if (!target) return;
target.textContent = target.textContent === text ? `${text}\u200b` : text;
};
// 拿起的状态:拖的是哪一项(item)、它在列表里的下标(index,按下时记)、项宽(width)、
// 按下时指针相对 list 左上角的位置(x0、y0)、当前指针位置(x)、最近 80ms 的 move 记录(samples)
let picked = null;
// 销毁以后 grab() 返回 null,不再改页面
let destroyed = false;
// 松手以后正在走的一件事:{ kind: 'bounce' | 'fly' | 'collapse', item, index, direction, timer, onEnd }
// (弹回、飞出去、收高度)。timer 和 onEnd 永远是这一件事现在挂着的定时器和 transitionend 监听——换阶段时先摘再挂
let ending = null;
// 立刻清干净一项的样式(不播过渡):先关过渡、清样式、强制回流,再把行内的 transition 清掉
const strip = (el) => {
el.style.transition = 'none';
el.style.translate = '';
el.style.opacity = '';
el.style.height = '';
el.style.margin = '';
el.style.padding = '';
el.style.borderTopWidth = '';
el.style.borderBottomWidth = '';
el.style.boxSizing = '';
el.style.overflow = '';
el.style.zIndex = '';
el.classList.remove('is-swiping');
void el.offsetHeight; // 强制回流:让清掉的样式在没有过渡的情况下先落定
el.style.transition = '';
};
// 摘掉正在走的这一件事挂着的监听和定时器(不动样式、不改 ending)
const unhook = () => {
clearTimeout(ending.timer);
ending.item.removeEventListener('transitionend', ending.onEnd);
};
// 把一项拿掉并发 dismiss:先清干净样式(页面拿到的是干净的元素,可以直接放回去),再拿掉,事件放在最后发——
// 页面监听 dismiss 读列表时,被移除的那一项已经不在了、剩下的项也没有残留样式;页面回调里可能调 destroy()(重新渲染),
// 所以调用方在它返回以后要重新看一眼 destroyed
const remove = (item, index, direction) => {
strip(item);
if (item.parentElement === list) list.removeChild(item);
list.dispatchEvent(new CustomEvent('dismiss', { detail: { item, index, direction }, bubbles: false }));
};
// 提交:弹回的回到原位;移除的拿掉、发 dismiss
const commit = () => {
if (!ending) return;
const { kind, item, index, direction } = ending;
unhook();
ending = null;
if (kind === 'bounce') strip(item);
else remove(item, index, direction);
};
// 中止(cancel()/destroy()):摘监听、清定时器、清样式,项留在原位,不改顺序、不发事件
const abort = () => {
if (!ending) return;
unhook();
strip(ending.item);
ending = null;
};
// 滑的时候这一项该是什么样:translate X = dx(跟着指针,没有过渡),透明度 = 1 - 0.6 × min(1, |dx| / 项宽)
const apply = (dx) => {
if (!picked) return;
picked.dx = dx;
picked.item.style.translate = `${dx.toFixed(1)}px 0`;
picked.item.style.opacity = String(Math.max(0, 1 - 0.6 * Math.min(1, Math.abs(dx) / picked.width)));
};
// 拿起:这一项加 is-swiping(CSS 里去掉过渡:跟手、不让文字被选中)、加阴影盖在邻居上面。
// 上一次松手以后的事还没走完就又拿起:先提交它——用户飞出去一条后零点几秒内又拿一条,上一次的移除不能悄悄丢掉;
// cancel()/destroy() 才是中止(不提交)
const grab = (item, x, y) => {
if (destroyed) return null;
if (ending) commit();
if (destroyed) return null; // commit() 末尾发 dismiss,页面的回调可能已经把整个控制对象 destroy 了
if (picked) cancel();
const width = item.getBoundingClientRect().width;
if (!(width > 0)) return null; // 项宽为 0(藏起来了):不拿起
const index = items().indexOf(item);
if (index < 0) return null; // 不是这个列表里的项(比如刚被移除的):不拿起
picked = { item, index, width, x0: x, y0: y, x, dx: 0, samples: [{ t: performance.now(), x }] };
item.style.transition = '';
item.classList.add('is-swiping');
item.style.zIndex = '1';
return picked;
};
const move = (x, y) => {
if (!picked) return;
picked.x = x;
picked.samples.push({ t: performance.now(), x });
// 只留最近 80ms 的记录(算松手速度用)
const cut = performance.now() - 80;
while (picked.samples.length > 1 && picked.samples[0].t < cut) picked.samples.shift();
apply(x - picked.x0);
};
// 松手前最近 80ms 的速度(px/ms,往右为正):只看这 80ms 里的 move 记录,首尾记录的位移除以时间差;
// 不足两笔记录时是 0——甩了一下再停住不动、过一会儿才松手,不算甩(手停住以后不会再有 move)
const velocity = () => {
if (!picked) return 0;
const cut = performance.now() - 80;
const recent = picked.samples.filter((s) => s.t >= cut);
if (recent.length < 2) return 0;
const a = recent[0];
const b = recent[recent.length - 1];
const dt = b.t - a.t;
return dt > 0 ? (b.x - a.x) / dt : 0;
};
// 收高度:项还在 DOM 里自己的位置上;高度、上下外边距、上下内边距过渡到 0(左右不动),
// 时长是 duration 的 80%,overflow: hidden 不让里面的内容露出来。收完 commit(拿掉、发事件)
const collapse = () => {
const item = ending.item;
unhook();
ending.kind = 'collapse';
const ms = Math.round(duration * 0.8);
const t = `${ms}ms var(--sd-easing)`;
item.style.transition = `height ${t}, margin ${t}, padding ${t}`;
item.style.overflow = 'hidden';
// 先改成 border-box 再量:项是 content-box 时,offsetHeight(含内边距和边框)写给 height(只是内容高)会先多出一截再往下收
item.style.boxSizing = 'border-box';
item.style.height = `${item.offsetHeight}px`;
void item.offsetHeight; // 先把行内 height 定在现在的值,下面的 0 才会过渡
// 上下边框的宽度不过渡(浏览器会把 0 到 1px 之间的边框都画成 1px,拖到最后一刻才消失,拿掉时后面的项会多跳一个边框的宽度):
// 一开始就去掉(这时项已经是透明的),border-box 的 height 不变,总高度不跳
item.style.borderTopWidth = '0px';
item.style.borderBottomWidth = '0px';
item.style.height = '0px';
item.style.marginTop = '0px';
item.style.marginBottom = '0px';
item.style.paddingTop = '0px';
item.style.paddingBottom = '0px';
// transitionend 会冒泡:只认这一项自己的 height 那一次
ending.onEnd = (e) => { if (e.target === item && e.propertyName === 'height') commit(); };
item.addEventListener('transitionend', ending.onEnd);
ending.timer = setTimeout(commit, ms + 80);
};
// 移除一条:先飞出去(translate 到 ±(项宽 + 40px)、透明度 0,duration、easing),再收高度,收完 commit(拿掉、发事件)。
// 开始时就念读屏提示(还剩几个 = 拿掉这一项以后列表里剩下的个数)。减少动态:不用过渡,同步完成(返回之前已经拿掉、事件已经发了)。
// direction 是 'left' 或 'right'。返回 true;销毁了、或这一项不在列表里时返回 null
const dismiss = (item, direction) => {
if (destroyed) return null;
if (ending) commit();
if (destroyed) return null;
const index = items().indexOf(item);
if (index < 0) return null;
if (picked && picked.item === item) picked = null; // 直接移除正拿着的那一项:手势到此为止
const message = sayings.removed(nameOf(item), items().length - 1);
// 减少动态:不用过渡,同步完成;读屏提示放在事件之后(页面在 dismiss 回调里可能重新渲染,见 say)
if (reduce()) { remove(item, index, direction); say(message); return true; }
say(message);
const sign = direction === 'left' ? -1 : 1;
const width = item.getBoundingClientRect().width || 0;
const fly = 'var(--sd-duration, 260ms) var(--sd-easing, cubic-bezier(0.2, 0, 0, 1))';
ending = { kind: 'fly', item, index, direction, timer: 0, onEnd: null };
item.style.transition = `translate ${fly}, opacity ${fly}`;
item.style.translate = `${sign * (width + 40)}px 0`;
item.style.opacity = '0';
item.classList.remove('is-swiping');
item.style.zIndex = '1';
ending.onEnd = (e) => { if (e.target === item && (e.propertyName === 'translate' || e.propertyName === 'opacity')) collapse(); };
item.addEventListener('transitionend', ending.onEnd);
ending.timer = setTimeout(collapse, Number(duration) + 80);
return true;
};
// 松手:|dx| ≥ threshold × 项宽,或最近 80ms 速度 ≥ 0.5 px/ms(朝着滑的方向)且 |dx| ≥ 40px:移除;否则弹回。
// 返回 { removed, index, direction }(没拿着时返回 null)
const drop = () => {
if (!picked) return null;
const held = picked;
// 上一次松手以后的事还没走完:先提交(它拿掉的那一项会发 dismiss,页面的回调里可能 destroy()、cancel()、又拿起别的)。
// 提交以后手势已经被回调中止了(销毁了,或者拿着的不是这一项了):什么都不做、不写样式、不挂定时器
if (ending) {
commit();
if (destroyed || picked !== held) return null;
}
const { item, index, width, dx } = held;
const v = velocity();
const direction = dx < 0 ? 'left' : 'right';
const sign = dx < 0 ? -1 : 1;
const fast = Math.abs(v) >= 0.5 && Math.sign(v) === sign && Math.abs(dx) >= 40;
const out = Math.abs(dx) >= (threshold / 100) * width || fast;
if (out) {
const ok = dismiss(item, direction);
if (!ok) { picked = null; strip(item); }
return { removed: Boolean(ok), index, direction };
}
picked = null;
// 弹回:translate 过渡回 0、透明度回 1(duration、easing)。和别的松手以后的事一样登记在 ending 里
item.classList.remove('is-swiping');
if (reduce()) { strip(item); return { removed: false, index, direction }; }
const back = 'var(--sd-duration, 260ms) var(--sd-easing, cubic-bezier(0.2, 0, 0, 1))';
item.style.transition = `translate ${back}, opacity ${back}`;
item.style.translate = '0px 0';
item.style.opacity = '1';
ending = { kind: 'bounce', item, index, direction, timer: 0, onEnd: null };
ending.onEnd = (e) => { if (e.target === item && (e.propertyName === 'translate' || e.propertyName === 'opacity')) commit(); };
item.addEventListener('transitionend', ending.onEnd);
ending.timer = setTimeout(commit, Number(duration) + 80);
return { removed: false, index, direction };
};
// 取消(pointercancel、失去捕获、键盘模式被接管):回到拿起之前的样子,不改顺序、不发事件。
// 还没走完的松手以后的事也一起中止(清定时器、摘监听、清样式),之后定时器不会再动页面、不会再发事件
const cancel = () => {
abort();
if (!picked) return;
const { item } = picked;
picked = null;
strip(item);
};
// ---- 鼠标和触摸(Pointer Events,监听在 list 上)----
// 正在被指针按着的:哪一项、哪个 pointerId、按下还没认定横滑(pending)还是已经拿起
let active = null;
const INTERACTIVE = 'a, button, input, textarea, select, [data-no-swipe]';
const onPointerDown = (e) => {
if (e.button !== 0) return;
if (!(e.target instanceof Element)) return;
if (e.target.closest(INTERACTIVE)) return; // 按在项里的按钮、链接上:不抢
const item = e.target.closest('li');
if (!item || item.parentElement !== list) return;
// 已经有指针在滑:忽略新的按下(第二根手指不抢)
if (active) return;
// 程序拿着一项(grab() 还没 drop)时又来了真的指针:先取消程序拿着的(全库同时只有一项被拿起)
if (picked) cancel();
active = { item, pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, captured: false };
};
const onPointerMove = (e) => {
if (!active || e.pointerId !== active.pointerId) return;
const dx = e.clientX - active.startX;
const dy = e.clientY - active.startY;
if (!active.captured) {
// 还没认定横滑:横向位移超过 6px 且 |dx| > |dy| 才拿起;dy 大就当竖滚,放弃(什么都不改)
if (Math.abs(dy) >= Math.abs(dx) && Math.abs(dy) > 6) { active = null; return; }
if (Math.abs(dx) <= 6 || Math.abs(dx) <= Math.abs(dy)) return;
const base = list.getBoundingClientRect();
const taken = grab(active.item, active.startX - base.left, active.startY - base.top);
if (!taken) { active = null; return; } // 项宽为 0:不拿起,指针的按下也作废
active.captured = true;
// 鼠标在文字上横着拖会拖出文字选区:认定横滑的这一刻清掉(拿起的项另有 user-select: none)
window.getSelection()?.removeAllRanges();
try { list.setPointerCapture(e.pointerId); } catch { /* 拿不到捕获时照样能滑 */ }
active.base = base;
}
move(e.clientX - active.base.left, e.clientY - active.base.top);
};
const onPointerUp = (e) => {
if (!active || e.pointerId !== active.pointerId) return;
const wasCaptured = active.captured;
active = null;
if (!wasCaptured) return; // 没认定横滑:这只是普通的按下松开(点了一下项里的字),什么都不做
drop();
};
// pointercancel(浏览器接手触摸滚动)或失去捕获:弹回,不移除,不发事件
const onPointerEnd = (e) => {
if (!active || e.pointerId !== active.pointerId) return;
const wasCaptured = active.captured;
active = null;
if (!wasCaptured) return;
cancel();
say(sayings.cancelled());
};
// ---- 键盘 ----
const onKeyDown = (e) => {
if (!(e.target instanceof Element)) return;
const item = e.target.closest('li');
if (!item || item.parentElement !== list || e.target.closest(INTERACTIVE)) return;
if (e.key !== 'Delete' && e.key !== 'Backspace') return;
// 指针正在滑:键盘不再起作用(全库只有一个模式)
if (active && active.captured) return;
e.preventDefault();
// 上一次松手以后的事先提交(它拿掉的那一项不能当成焦点的下一个)
if (ending) commit();
if (destroyed) return;
const index = items().indexOf(item);
const rest = items().filter((el) => el !== item);
// 焦点给下一项(没有下一项给上一项,都没有就不动):先挪焦点、再移除——减少动态时移除是同步的,dismiss 回调里页面想把焦点放到别处
// (比如"撤销"按钮)时,看到的就是最终的焦点,不会被盖掉
const next = rest[index] ?? rest[index - 1] ?? null;
if (next) next.focus({ preventScroll: true });
dismiss(item, 'left');
};
const listeners = [
[list, 'pointerdown', onPointerDown],
[list, 'pointermove', onPointerMove],
[list, 'pointerup', onPointerUp],
[list, 'pointercancel', onPointerEnd],
[list, 'lostpointercapture', onPointerEnd],
[list, 'keydown', onKeyDown],
];
for (const [target, type, fn] of listeners) target.addEventListener(type, fn);
// 项上加 tabindex="0"(键盘要用):只给还没有 tabindex 的项加(页面自己写过 -1 的尊重它);destroy() 时只摘自己加的
const tabbed = items().filter((el) => !el.hasAttribute('tabindex'));
for (const el of tabbed) el.setAttribute('tabindex', '0');
const ctl = {
grab, move, drop, cancel, dismiss,
destroy() {
destroyed = true;
abort();
if (picked) { const { item } = picked; picked = null; strip(item); }
for (const [target, type, fn] of listeners) target.removeEventListener(type, fn);
for (const el of tabbed) { if (el.getAttribute('tabindex') === '0') el.removeAttribute('tabindex'); }
list.style.removeProperty('--sd-duration');
list.style.removeProperty('--sd-easing');
active = null;
live.remove();
if (prevs.get(list) === ctl) prevs.delete(list);
},
};
prevs.set(list, ctl);
return ctl;
}HTML
<!-- 滑走移除:列表加上 class="sd-list"(配合 swipe-dismiss.js),每一项就是一个 <li>,整项都是手势的区域 -->
<!-- 项里放按钮、链接时要照常能点(脚本不会抢);有不想被滑走的部分给它加 data-no-swipe -->
<!-- 项之间的间距写成项自己的 margin-bottom,不要用 flex/grid 的 gap:收高度收的是项自己的外边距,gap 要到项拿掉的那一刻才消失,后面的项会跳一下 -->
<ul class="sd-list" id="inbox">
<li>9:02 收到一条新留言</li>
<li>10:15 订阅的周刊到了</li>
<li>11:40 服务器备份完成</li>
</ul>
<script type="module">
import { swipeDismiss } from './swipe-dismiss.js';
const list = document.getElementById('inbox');
swipeDismiss(list, { threshold: 40, duration: 260, easing: 'cubic-bezier(0.2, 0, 0, 1)' });
// 被移除时保存(这里只打出来;item 是被拿掉的元素,要撤销可以放回去)
list.addEventListener('dismiss', (e) => console.log(`移除了第 ${e.detail.index + 1} 条(向${e.detail.direction === 'left' ? '左' : '右'})`));
</script>