# 拖拽换位排序（Drag to reorder）

- 俗称：按住一项拖到别的位置排序；拖着列表项换位置；待办事项拖动排序；拖拽调整顺序
- 用在：卡片列表（个人网站、作品集、工具站）
- 触发：点击
- 感觉：利落、俏皮
- 版本：1，更新于 2026-11-05

## 原理

拖的时候别的项用位移让开（不改页面结构，不会一直重排），松手落下才一次性改顺序、清掉位移；手柄上关掉浏览器自己的触摸手势，别的地方照常滚动；键盘也能拿起、移动、放下，读屏有提示；只支持每项一样高的竖排列表。

适合：待办清单排优先级、一列竖排的卡片和图片调顺序：让人自己安排顺序的地方（只支持每项一样高的竖排列表，横排的看板、图片墙要换别的做法）。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `duration` | 让位和落下的时长 | 200ms | 100–400ms |
| `lift` | 拿起时的放大 | 1.04倍 | 1–1.12倍 |
| `easing` | 缓动 | cubic-bezier(0.2, 0, 0, 1) | — |

## 质量要求

- 开启"减少动态"时：让位和落位不用过渡，直接到位；拿起不放大；顺序照常能改。
- 手机上：手柄至少 44×44px 好按；只在手柄上关掉浏览器自己的触摸手势（touch-action: none），列表其余地方照常滚动。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

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

```text
请在我的项目里给卡片列表加上「拖拽换位排序」（Drag to reorder）效果：拖的时候别的项用位移让开（不改页面结构，不会一直重排），松手落下才一次性改顺序、清掉位移；手柄上关掉浏览器自己的触摸手势，别的地方照常滚动；键盘也能拿起、移动、放下，读屏有提示；只支持每项一样高的竖排列表。
参数：让位和落下的时长 200ms，拿起时的放大 1.04倍，缓动 cubic-bezier(0.2, 0, 0, 1)。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/drag-reorder.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<!-- 拖拽换位排序：列表的每一项里放一个手柄按钮（class="drag-handle"），列表加上 class="dr-list" -->
<!-- 手柄的无障碍名建议写上项的名字（aria-label="拖动排序：xxx"）：Tab 过去才听得出是哪一项，纯"拖动排序"分不清 -->
<ul class="dr-list" id="todos">
  <li>
    <button type="button" class="drag-handle" aria-label="拖动排序：写完这周的周报">⋮⋮</button>
    <span>写完这周的周报</span>
  </li>
  <li>
    <button type="button" class="drag-handle" aria-label="拖动排序：把想法画成草图">⋮⋮</button>
    <span>把想法画成草图</span>
  </li>
  <li>
    <button type="button" class="drag-handle" aria-label="拖动排序：给新效果想名字">⋮⋮</button>
    <span>给新效果想名字</span>
  </li>
</ul>
<script type="module">
  import { dragReorder } from './drag-reorder.js';
  const list = document.getElementById('todos');
  dragReorder(list, { duration: 200, lift: 1.04, easing: 'cubic-bezier(0.2, 0, 0, 1)' });
  // 放下并换了位置时保存新顺序（这里只打出来）
  list.addEventListener('reorder', (e) => console.log(`第 ${e.detail.from + 1} 项移到了第 ${e.detail.to + 1} 项`));
</script>
```

CSS：

```css
/* 拖拽换位排序（Drag to reorder）的样式，配合 drag-reorder.js。脚本给正在拖的那一项加 class="is-dragging"，
   按参数设置 --dr-duration、--dr-easing；让位和落位的过渡都靠这里（拖动中的那一项除外：它跟指针走，不过渡）。
   拿起时的影子写在 --dr-shadow 里。开启"减少动态"时不用过渡（直接到位）、不放大，顺序和事件照常。 */
.dr-live {
  position: absolute;
  width: 1px;
  height: 1px;
  margin: -1px;
  clip-path: inset(50%);
  overflow: hidden;
  white-space: nowrap;
}
/* 手柄：touch-action 只写在手柄上，列表其余地方照常滚动；至少 44×44px 好按（手机上也是） */
.drag-handle {
  touch-action: none;
  min-width: 44px;
  min-height: 44px;
}
/* 让位和落下：时长、缓动来自参数；拖动中的那一项去掉过渡（跟指针走） */
.dr-list > * {
  transition: translate var(--dr-duration, 200ms) var(--dr-easing, cubic-bezier(0.2, 0, 0, 1));
}
/* 拿起的那一项：position 让 z-index 生效（普通 ul > li 没有 position，z-index 不起作用，会被让位的邻居盖住）。
   position 写在 :where() 里（不占优先级）：项自己写了别的定位（absolute、sticky）就用它的 */
:where(.dr-list > .is-dragging) {
  position: relative;
}
.dr-list > .is-dragging {
  z-index: 1;
  box-shadow: var(--dr-shadow, 0 14px 28px -12px rgb(0 0 0 / 0.4));
  transition: none;
}
/* 减少动态：让位和落位不用过渡。脚本的 ignoreReducedMotion 选项（演示强制播放）会给列表加 data-dr-motion，有它就不关 */
@media (prefers-reduced-motion: reduce) {
  .dr-list:not([data-dr-motion]) > * { transition: none; }
}
```

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

```js
// 拖拽换位排序（Drag to reorder）· 原生 JS，不依赖任何库。
// 参考 StyleKit 的 drag-physics、Animation Handbook 的 drag-to-reorder、Motion Lexicon 的 drag-to-reorder 的做法（三者都是 MIT），自己实现，没有复制代码：
// 拖的时候别的项用 translate 让位、不改 DOM 顺序，松开落下以后才一次性 insertBefore——照这个通行的做法写的。
// list 是一个列表（配合 drag-reorder.css，给列表加上 class="dr-list"），它的每个子元素是一项（<li>），项里有一个手柄
// <button type="button" class="drag-handle" aria-label="拖动排序：这一项的名字">（手柄是项的直接子元素，无障碍名里写上项的名字，
// Tab 过去才听得出是哪一项；名字只给人听，脚本不读它）。没有脚本时它就是一个普通列表，内容和顺序不变。
// 按住手柄上下拖：这一项"拿起"（放大 lift 倍、加阴影、盖在别的项上面），跟着指针走；这一项的中心越过哪一项的中心，
// 被越过的那几项就朝反方向挪开"一项的高度加间距"（translate，用 duration、easing 的 CSS 过渡让开）；松开落到新位置
// （同样的时长和缓动），落下以后才一次性改 DOM 顺序（insertBefore），同时清掉所有项的样式（改顺序和清样式在同一帧，看起来不跳）；位置没变就不改。
// 键盘（手柄是 button，Tab 能到）：空格或回车"拿起"，上下箭头一格一格地移动（让位的样子和鼠标一样），再按空格或回车放下，Esc 取消
// （指针拖动中想放弃，把这一项拖回原来的位置再松手：落回原位不改顺序、不发事件；Esc 只在键盘拿起时取消）；
// 读屏提示写在 list 后面一个 aria-live="polite"、视觉上隐藏的元素里（destroy() 时移除）。提示的句子可以用 messages 选项换成别的语言
// （picked、moved、dropped、cancelled 四个函数），不传就是中文。
// 触摸和鼠标都走 Pointer Events（只在手柄上认按下；手柄 touch-action: none 写在 CSS 里，列表其余地方照常滚动）。
// 全库同时只有一个拿起：指针按住时忽略别的指针按下；键盘拿起还没放下时指针按住别的项，先取消键盘拿起再开始拖。
// 放下并且位置变了，在 list 上触发 CustomEvent('reorder', { detail: { from, to } })（下标从 0 开始），让页面能保存新顺序；位置没变不触发。
// 返回 { grab(item, y), move(y), drop(), cancel(), destroy() }：鼠标、触摸、键盘内部也走这几个（演示和检查用它们控制）；
// 销毁以后 grab() 返回 null，不再改页面。
// y 是指针相对 list 顶边的位置（list 自己的像素）。对同一个 list 重复调用 dragReorder，先 destroy 旧的（不会重复监听）。
// 开启"减少动态"时：让开和落位不用过渡（直接到位），拿起也不放大；顺序和事件照常（drag-reorder.css 里关掉过渡；选项 ignoreReducedMotion 只给演示强制播放用，
// 它会给列表加上 data-dr-motion 属性，CSS 里的减少动态媒体查询就不再关掉让位的过渡）。
// 只支持项高相同的竖排列表：项高不同会落错格；横排或项高加间距算出来不是正数（pitch 为 0、负数、NaN）时不拿起，也不触发任何事；
// 拖动中容器滚动、列表被外部增删项都不处理，要改列表先 destroy()。

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

export function dragReorder(list, {
  duration = 200,
  lift = 1.04,
  easing = 'cubic-bezier(0.2, 0, 0, 1)',
  ignoreReducedMotion = false,
  messages = {},
} = {}) {
  prevs.get(list)?.destroy();
  // duration、easing 写进列表的 CSS 变量：让位（.dr-list > * 的过渡）和落位（行内过渡）都用它们
  list.style.setProperty('--dr-duration', `${duration}ms`);
  list.style.setProperty('--dr-easing', easing);
  // 演示强制播放（ignoreReducedMotion）：CSS 里 @media (prefers-reduced-motion) 关让位过渡时认这个属性，有它就不关
  if (ignoreReducedMotion) list.setAttribute('data-dr-motion', '');
  const reduce = () => !ignoreReducedMotion && matchMedia('(prefers-reduced-motion: reduce)').matches;
  const items = () => [...list.children].filter((el) => el instanceof HTMLElement);
  const handleOf = (item) => item.querySelector('.drag-handle');
  // 项的名字：不带手柄上的字（比如 ⋮⋮）
  const nameOf = (item) => {
    const clone = item.cloneNode(true);
    clone.querySelectorAll('.drag-handle').forEach((h) => h.remove());
    return (clone.textContent || '').trim().replace(/\s+/g, ' ');
  };
  // 读屏提示：默认中文，句子用 messages 选项换语言。
  // 每次在句尾交替加/不加一个零宽空格（U+200B）：相同的句子连续两次时 textContent 不一样，读屏才会念第二次
  const sayings = {
    picked: messages.picked ?? ((name, n, total) => `已拿起：${name}，现在第 ${n} 个，共 ${total} 个。上下箭头移动，空格放下，Esc 取消`),
    moved: messages.moved ?? ((n, total) => `移到第 ${n} 个，共 ${total} 个`),
    dropped: messages.dropped ?? ((name, n, total) => `已放下：${name}，现在第 ${n} 个，共 ${total} 个`),
    cancelled: messages.cancelled ?? (() => '已取消'),
  };

  // 读屏提示
  const live = document.createElement('div');
  live.setAttribute('aria-live', 'polite');
  live.setAttribute('aria-atomic', 'true'); // 每次整句替换，读屏要整句念，不是只念变了的几个字
  live.className = 'dr-live';
  list.after(live);
  let zwsp = false;
  // 页面在 reorder 回调里重新 dragReorder(同一个 list)（先 destroy 旧的）时，回调返回以后这里才念"已放下"——
  // 旧的活区已经被移走了，改写到 list 后面紧挨着的那个新活区；没有就什么都不写
  const say = (text) => {
    const target = live.isConnected ? live : (list.nextElementSibling?.matches('.dr-live') ? list.nextElementSibling : null);
    if (!target) return;
    target.textContent = text + (zwsp ? '\u200b' : '');
    zwsp = !zwsp;
  };

  // 拿起的状态：拖的是哪一项（item）、它在列表里原来的下标（from）、指针相对 list 顶边的位置（y）、
  // 指针按住时离这一项顶边多远（grabAt）、这一项被谁按着（pointer / key）
  let picked = null;
  // 销毁以后 grab() 返回 null，不再改页面（页面在 reorder 回调里 destroy 以后，被点名的项不能被拿起）
  let destroyed = false;
  // 每一项没被 translate 挪动时离 list 顶边多远（tops）和"一项的高度加间距"（pitch）；拖动中不用重量
  let metrics = null;
  const measure = () => {
    const all = items();
    const base = list.getBoundingClientRect().top;
    const tops = all.map((el) => el.getBoundingClientRect().top - base);
    const pitch = tops.length > 1 ? tops[1] - tops[0] : (all[0] ? all[0].offsetHeight : 0);
    metrics = { tops, pitch, count: all.length };
    return metrics;
  };
  // 这一项现在算在第几个槽位（0 起）：它的顶边加半格的高度，四舍五入到最近的槽位（中心越过哪一项的中心就算过去）
  const slotOf = (y) => {
    const m = metrics || measure();
    const top = y - (picked ? picked.grabAt : 0);
    const k = Math.round((top - m.tops[0]) / m.pitch);
    return Math.max(0, Math.min(m.count - 1, k));
  };

  // 记每一项最后一次写进 style.translate 的字符串：值没变就不写。不能把 el.style.translate 读回来比——
  // 浏览器读回来的是序列化过的字符串（写 "0 -64.0px" 读回 "0px -64px"），永远和要写的不相等，每次移动都会白写一遍。strip() 清样式时清掉这张表
  let written = new Map();
  const write = (el, value) => {
    if ((written.get(el) ?? '') === value) return;
    el.style.translate = value;
    written.set(el, value);
  };

  // 让位：不改 DOM 顺序，只改 translate。被拖的那一项跟指针走（它不过渡）；被越过的那几项朝反方向挪开一格。
  // 被拖那一项的位移是相对它原来的位置（拿下不动时是 0，指针挪多少它挪多少），不是"离列表顶边多远"：
  // 拿着走到头被夹在最后一个（或第一个）槽位，到不了的地方去不了
  const apply = (y) => {
    if (!picked) return;
    const m = metrics || measure();
    const slot = slotOf(y);
    // 夹在第一个和最后一个槽位之间（tops[0] 不一定是 0：列表有上内边距时第一个槽位在列表顶边下面）
    const top = Math.max(m.tops[0], Math.min(m.tops[m.count - 1], y - picked.grabAt));
    const px = `0 ${(top - m.tops[picked.from]).toFixed(1)}px`;
    write(picked.item, px);
    picked.y = y;
    items().forEach((el, i) => {
      if (el === picked.item) return;
      let shifted = 0;
      if (i > picked.from && i <= slot) shifted = -m.pitch; // 拖下去：越过的项往上挪
      else if (i < picked.from && i >= slot) shifted = m.pitch; // 拖上来：让出来的项往下挪
      write(el, shifted ? `0 ${shifted.toFixed(1)}px` : '');
    });
  };

  // 正在落下（上一回的过渡没走完）时的收尾：定时器 id、transitionend 监听（挂在哪一项上、哪个函数）
  let landing = null;

  // 立刻收干净所有项的样式（不播过渡）：先给所有项行内 transition: none、清 translate/z-index/scale/is-dragging，
  // 强制回流（void list.offsetHeight）让"不过渡"先落定，再把行内的 transition 清掉（回到 CSS 里的设置）。
  // finish()（落位提交）、cancel()、destroy()、中止落位都用它
  const strip = () => {
    written = new Map();
    for (const el of items()) el.style.transition = 'none';
    for (const el of items()) {
      el.style.translate = '';
      el.style.zIndex = '';
      el.style.scale = '';
      el.classList.remove('is-dragging');
    }
    void list.offsetHeight; // 强制回流：让清掉的样式在没有过渡的情况下先落定
    for (const el of items()) el.style.transition = '';
  };

  // 中止还没走完的落位：清定时器、摘 transitionend 监听、清样式。不改顺序、不发事件——
  // 页面在落位过渡期间 cancel()/destroy() 时，这一下之后就不再有任何动作
  const abortLanding = () => {
    if (!landing) return;
    clearTimeout(landing.timer);
    landing.item.removeEventListener('transitionend', landing.onEnd);
    landing = null;
    strip();
  };

  // 拿起：放大（减少动态时不放大）、加阴影和 z-index（class 里）；行内的 transition 清掉，听 CSS 的。
  // 横排或项高加间距不是正数（pitch 为 0、负数、NaN）时不拿起：算槽位会除以它，除坏了顺序就乱。
  // 上一次松手的落位还没走完就又拿起：先提交它（settle：改顺序、发 reorder）——用户松手后零点几秒内拖另一项，
  // 上一次的换位不能悄悄丢掉（页面监听 reorder 存的顺序会和画面对不上）；cancel()/destroy() 才是中止落位（不提交）
  const grab = (item, y) => {
    if (landing) landing.settle(); // 销毁时落位已经被中止（landing 是 null），这一句不会动页面
    if (destroyed) return null; // 销毁了；或者 settle() 在 finish() 末尾发 reorder，页面的回调把整个控制对象 destroy 了
    if (picked) cancel();
    measure();
    if (!(metrics.pitch > 0)) return null;
    const from = items().indexOf(item);
    picked = { item, from, y, grabAt: y - metrics.tops[from] };
    item.style.transition = '';
    item.classList.add('is-dragging');
    item.style.zIndex = '1';
    if (!reduce()) item.style.scale = String(lift);
    apply(y);
    return picked;
  };

  const move = (y) => { if (picked) apply(y); };

  // 放下：这一项过渡到它现在对应的空位（同样的时长和缓动），落下以后一次性改 DOM 顺序、清掉所有项的样式。
  // 改顺序和清样式在同一帧，看起来不跳；位置没变（落回原位）就不改顺序、不触发事件。返回 { from, to }（没拿着时返回 null）
  const drop = () => {
    if (!picked) return null;
    const { item, from } = picked;
    const m = metrics || measure();
    const slot = slotOf(picked.y);
    // 焦点是不是在被拖的这一项里：改 DOM 顺序会把这一项挪走，浏览器把焦点丢给 body；
    // 记下来，提交完把焦点还给它的手柄（键盘操作才接得上后面的按键）
    const hadFocus = list.contains(document.activeElement) && item.contains(document.activeElement);
    const handle = handleOf(item);
    picked = null;
    // 落位的收尾统一在 finish() 开头做：定时器、transitionend 监听不管是走完、兜底、还是被 grab() 里的
    // landing.settle() 提交调来的，都先摘掉再干活（不带走监听和定时器）。不用过渡直接收的分支里
    // timer、onEnd 还没赋值（初值 0 / null），摘了也不碍事
    let timer = 0;
    let onEnd = null;
    const finish = () => {
      clearTimeout(timer);
      if (onEnd) item.removeEventListener('transitionend', onEnd);
      landing = null;
      // 要发的 reorder 事件先记下，放到最后（清完样式、还了焦点之后）再发：
      // 页面监听这个事件读位置、用新顺序重新渲染，不该看到"顺序换了、位移还没清"的中间状态
      let fired = null;
      if (slot !== from) {
        const all = items();
        list.insertBefore(item, all[slot + (slot > from ? 1 : 0)] ?? null);
        fired = { detail: { from, to: slot } };
      }
      strip();
      metrics = null;
      handle?.setAttribute('aria-pressed', 'false');
      if (hadFocus) handle?.focus({ preventScroll: true }); // 焦点原来在这一项里：还给它（改顺序弄丢的）
      if (fired) list.dispatchEvent(new CustomEvent('reorder', { ...fired, bubbles: false }));
    };
    // 这一项目前挪到哪了、该落到哪：差得远时先过渡到位（is-dragging 平时不过渡位移，这里行内开回来），
    // 过渡走完（或到点兜底）再改顺序；差一点或不用过渡（减少动态）就直接收
    const current = parseFloat(getComputedStyle(item).translate.split(' ')[1] || '0') || 0;
    const target = m.tops[slot] - m.tops[from];
    if (reduce() || Math.abs(target - current) < 2) { finish(); return { from, to: slot }; }
    item.style.transition = 'translate var(--dr-duration, 200ms) var(--dr-easing, cubic-bezier(0.2, 0, 0, 1)), scale var(--dr-duration, 200ms) var(--dr-easing, cubic-bezier(0.2, 0, 0, 1))';
    item.style.translate = `0 ${target.toFixed(1)}px`;
    let settled = false;
    const settle = () => { if (settled) return; settled = true; finish(); };
    // transitionend 会冒泡：项里子元素（图标变色、徽章淡出）的过渡也会上来，只认这一项自己的 translate 那一次
    onEnd = (e) => { if (e.target !== item || e.propertyName !== 'translate') return; settle(); };
    item.addEventListener('transitionend', onEnd);
    timer = setTimeout(settle, duration + 80);
    landing = { item, onEnd, timer, settle };
    return { from, to: slot };
  };

  // 取消（pointercancel、失去捕获、Esc、键盘拿起被指针接管）：回到拿起之前的样子，不改顺序。
  // 还没走完的落位也一起中止（清定时器、摘监听、清样式），之后定时器不会再改顺序、不会再发事件
  const cancel = () => {
    abortLanding();
    if (!picked) return;
    const { item } = picked;
    picked = null;
    strip();
    metrics = null;
    handleOf(item)?.setAttribute('aria-pressed', 'false');
  };

  // ---- 鼠标和触摸（Pointer Events）----
  // 正在被指针按着的：哪一项、哪个 pointerId
  let active = null;
  // 键盘拿起的那一项
  let keyState = null;

  const itemOfHandle = (handle) => {
    const item = handle.parentElement;
    return item && item.parentElement === list ? item : null;
  };
  const onPointerDown = (e) => {
    if (e.button !== 0) return;
    const handle = e.target instanceof Element ? e.target.closest('.drag-handle') : null;
    if (!handle || !list.contains(handle)) return;
    // 已经有指针在拖：忽略这次新的按下（第二根手指抢不走第一根的拖拽）
    if (active) return;
    e.preventDefault();
    // 键盘还拿着：先取消键盘拿起，全库只剩指针这一个模式（读屏还以为拿着，会和画面、念的项对不上）
    if (keyState) {
      cancel();
      say(sayings.cancelled());
      keyState = null;
    }
    const item = itemOfHandle(handle);
    if (!item) return;
    try { handle.setPointerCapture(e.pointerId); } catch { /* 拿不到捕获时照样能拖，只是指针跑出窗口后收不到松开 */ }
    handle.setAttribute('aria-pressed', 'true');
    active = { item, pointerId: e.pointerId };
    const taken = grab(item, e.clientY - list.getBoundingClientRect().top);
    if (!taken) { // 横排或 pitch 不是正数：没拿起，指针的按下也作废
      active = null;
      handle.setAttribute('aria-pressed', 'false');
      return;
    }
    say(sayings.picked(nameOf(item), items().indexOf(item) + 1, items().length));
  };
  const onPointerMove = (e) => {
    if (!active || e.pointerId !== active.pointerId) return;
    move(e.clientY - list.getBoundingClientRect().top);
  };
  const onPointerUp = (e) => {
    if (!active || e.pointerId !== active.pointerId) return;
    const { item } = active;
    active = null;
    const where = drop();
    if (where && where.to !== where.from) say(sayings.dropped(nameOf(item), where.to + 1, items().length));
  };
  // pointercancel（浏览器接手触摸滚动）或失去捕获：回原样，不改顺序
  const onPointerEnd = (e) => {
    if (!active || e.pointerId !== active.pointerId) return;
    active = null;
    cancel();
    say(sayings.cancelled());
  };

  // ---- 键盘 ----
  const onKeyDown = (e) => {
    const handle = e.target instanceof Element ? e.target.closest('.drag-handle') : null;
    if (!handle || !list.contains(handle)) return;
    const item = itemOfHandle(handle);
    if (!item) return;
    // 指针正在拖：键盘不再起作用（空格去拿起会把指针的拖拽取消掉、读屏念的项也和画面对不上）
    if (active) return;
    const grabbing = keyState === item;
    if (e.key === ' ' || e.key === 'Enter') {
      e.preventDefault();
      if (grabbing) {
        keyState = null; // 先清掉：放下要改 DOM 顺序，改的时候浏览器会发 focusout（焦点短暂丢给 body），那不算"走开"
        const where = drop() || { to: items().indexOf(item) };
        say(sayings.dropped(nameOf(item), where.to + 1, items().length));
      } else {
        const taken = grab(item, (metrics || measure()).tops[items().indexOf(item)] + (metrics || measure()).pitch / 2);
        if (!taken) return; // 横排或 pitch 不是正数：不拿起，也不改 aria-pressed
        handle.setAttribute('aria-pressed', 'true');
        keyState = item;
        say(sayings.picked(nameOf(item), items().indexOf(item) + 1, items().length));
      }
      return;
    }
    if (e.key === 'Escape' && grabbing) {
      e.preventDefault();
      cancel();
      say(sayings.cancelled());
      keyState = null;
      return;
    }
    if (!grabbing || !picked) return;
    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
      e.preventDefault();
      const m = metrics || measure();
      const slot = slotOf(picked.y);
      const next = Math.max(0, Math.min(m.count - 1, slot + (e.key === 'ArrowDown' ? 1 : -1)));
      if (next === slot) return;
      move(picked.y + (next - slot) * m.pitch);
      say(sayings.moved(next + 1, m.count));
    }
  };

  // 键盘拿起期间，焦点走出这一项（Tab 到别处、点到别处）就取消：不然这一项停在"拿起"的样子，读屏也不知道还拿着。
  // focusout 的目标是这一项里的元素、焦点去了这一项以外（relatedTarget 不在这一项里，或干脆没有——比如窗口失焦）才算走开。
  // 我们自己改顺序引起的失焦不算：键盘放下时先把 keyState 清掉再调 drop()，这里就查不到"拿着"了
  const onFocusOut = (e) => {
    if (!keyState) return;
    if (!(e.target instanceof Element) || !keyState.contains(e.target)) return;
    if (e.relatedTarget && keyState.contains(e.relatedTarget)) return;
    cancel();
    say(sayings.cancelled());
    keyState = null;
  };

  const listeners = [
    [list, 'pointerdown', onPointerDown],
    [list, 'pointermove', onPointerMove],
    [list, 'pointerup', onPointerUp],
    [list, 'pointercancel', onPointerEnd],
    [list, 'lostpointercapture', onPointerEnd],
    [list, 'keydown', onKeyDown],
    [list, 'focusout', onFocusOut],
  ];
  for (const [target, type, fn] of listeners) target.addEventListener(type, fn);

  const ctl = {
    grab, move, drop, cancel,
    destroy() {
      destroyed = true;
      for (const [target, type, fn] of listeners) target.removeEventListener(type, fn);
      cancel(); // 里头先中止还没走完的落位（清定时器、摘监听），再清拿起的样式
      for (const el of items()) {
        el.classList.remove('is-dragging');
        el.style.translate = '';
        el.style.zIndex = '';
        el.style.scale = '';
        el.style.transition = '';
        handleOf(el)?.setAttribute('aria-pressed', 'false');
      }
      list.style.removeProperty('--dr-duration');
      list.style.removeProperty('--dr-easing');
      list.removeAttribute('data-dr-motion');
      active = null;
      keyState = null;
      live.remove();
      if (prevs.get(list) === ctl) prevs.delete(list);
    },
  };
  prevs.set(list, ctl);
  return ctl;
}
```

## 出处

- 参考 StyleKit drag-physics、Animation Handbook drag-to-reorder、Motion Lexicon drag-to-reorder 的做法（拖时让位、落下改顺序），自己实现，没有复制代码
