# 长按填充确认（Hold to confirm）

- 俗称：长按按钮填充确认；按住进度条走满才触发；防误触长按删除；长按确认操作
- 用在：按钮（工具和应用、个人网站）
- 触发：点击
- 感觉：利落、戏剧化
- 版本：1，更新于 2026-11-17

## 原理

在按钮底层放一层左对齐的填充层（transform-origin: left），按下鼠标、触屏或键盘空格/回车时启动 Web Animations API 将 scaleX 从 0 拉到 1；若在设定的长按时长内松手或移开，则取消填充并平滑退回 0 且不触发事件；只有动画完整走满才派发 confirm 自定义事件；同时用输入锁避免多指或鼠标键盘互相抢占。

适合：删除数据、注销账号、清空记录等不可逆操作，防止用户不小心点一下就立刻执行。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `duration` | 长按时长 | 900ms | 400–2500ms |
| `easing` | 缓动 | linear | — |

## 质量要求

- 开启"减少动态"时：保留长按计时防误触，关闭按压微缩与平滑回退过渡，进度直接切换并触发确认。
- 手机上：禁用长按弹出系统文本选择菜单（user-select: none / touch-action: manipulation），按钮高度不少于 44px。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

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

```text
请在我的项目里给按钮加上「长按填充确认」（Hold to confirm）效果：在按钮底层放一层左对齐的填充层（transform-origin: left），按下鼠标、触屏或键盘空格/回车时启动 Web Animations API 将 scaleX 从 0 拉到 1；若在设定的长按时长内松手或移开，则取消填充并平滑退回 0 且不触发事件；只有动画完整走满才派发 confirm 自定义事件；同时用输入锁避免多指或鼠标键盘互相抢占。
参数：长按时长 900ms，缓动 linear。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/hold-to-confirm.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<button type="button" class="htc-btn" id="delete-btn">
  <span class="htc-fill" aria-hidden="true"></span>
  <span class="htc-label">长按删除</span>
</button>

<script type="module">
  import { holdToConfirm } from './hold-to-confirm.js';
  const btn = document.getElementById('delete-btn');
  holdToConfirm(btn, {
    duration: 900,
    onConfirm: () => { btn.querySelector('.htc-label').textContent = '已确认删除'; },
  });
</script>
```

CSS：

```css
/* 长按填充确认（Hold to confirm）样式，配合 hold-to-confirm.js。 */
.htc-btn {
  position: relative;
  display: inline-grid;
  place-items: center;
  min-height: 44px;
  padding: 0 20px;
  border: 1.5px solid var(--htc-border, currentColor);
  border-radius: 10px;
  background: transparent;
  color: inherit;
  font: inherit;
  font-weight: 700;
  overflow: hidden;
  cursor: pointer;
  user-select: none;
  -webkit-user-select: none;
  touch-action: manipulation;
  transition: transform 0.14s ease;
}

.htc-btn.is-holding {
  transform: scale(0.97);
}

.htc-fill {
  position: absolute;
  inset: 0;
  background: var(--htc-fill, currentColor);
  opacity: 0.18;
  transform-origin: left center;
  transform: scaleX(0);
  pointer-events: none;
}

.htc-btn.is-confirmed .htc-fill {
  opacity: 1;
  transform: scaleX(1);
}

.htc-btn.is-confirmed .htc-label {
  color: var(--htc-done-ink, #ffffff);
}

.htc-label {
  position: relative;
  z-index: 1;
  pointer-events: none;
}

@media (prefers-reduced-motion: reduce) {
  .htc-btn:not(.htc-force) {
    transition: none;
  }
  .htc-btn:not(.htc-force).is-holding {
    transform: none;
  }
}
```

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

```js
// 长按填充确认（Hold to confirm）参考实现。
// 用法：<button class="htc-btn"><span class="htc-fill"></span><span class="htc-label">长按确认</span></button>
// 调 const ctl = holdToConfirm(btn, { duration: 900, easing: 'linear', onConfirm: () => {} }); 销毁调 ctl.destroy()。

export function holdToConfirm(btn, {
  duration = 900,
  easing = 'linear',
  onConfirm = null,
  ignoreReducedMotion = false,
} = {}) {
  if (!(btn instanceof Element)) return null;
  const fill = btn.querySelector('.htc-fill');
  if (!fill) return null;

  const dur = Number(duration) || 900;
  const easeStr = String(easing);
  const reduceQuery = typeof matchMedia === 'function' ? matchMedia('(prefers-reduced-motion: reduce)') : null;
  const isReduced = () => Boolean(reduceQuery?.matches && !ignoreReducedMotion);

  btn.classList.add('htc-btn');
  if (ignoreReducedMotion) btn.classList.add('htc-force');

  let activeMode = null; // 'pointer' | 'key' | 'program' | null
  let activePointerId = null;
  let confirmed = false;
  let destroyed = false;
  let fillAnim = null;
  let holdTimer = 0;

  const clearTimers = () => {
    if (holdTimer) { clearTimeout(holdTimer); holdTimer = 0; }
    if (fillAnim) { fillAnim.cancel(); fillAnim = null; }
  };

  const commitConfirm = () => {
    if (destroyed || confirmed) return;
    clearTimers();
    activeMode = null;
    activePointerId = null;
    confirmed = true;
    btn.classList.remove('is-holding');
    btn.classList.add('is-confirmed');
    fill.style.transform = 'scaleX(1)';
    if (typeof onConfirm === 'function') onConfirm();
    if (destroyed) return;
    btn.dispatchEvent(new CustomEvent('confirm', { bubbles: true }));
  };

  const startHold = (mode, pointerId = null) => {
    if (destroyed || confirmed || activeMode !== null) return;
    activeMode = mode;
    activePointerId = pointerId;
    btn.classList.add('is-holding');
    clearTimers();
    if (isReduced()) {
      fill.style.transform = 'scaleX(0.35)';
      holdTimer = setTimeout(commitConfirm, dur);
    } else {
      fillAnim = fill.animate(
        [{ transform: 'scaleX(0)' }, { transform: 'scaleX(1)' }],
        { duration: dur, easing: easeStr, fill: 'forwards' },
      );
      fillAnim.finished.then(() => {
        if (!destroyed && activeMode === mode) commitConfirm();
      }).catch(() => undefined);
    }
  };

  const cancelHold = (mode) => {
    if (destroyed || confirmed || (mode && activeMode !== mode)) return;
    activeMode = null;
    activePointerId = null;
    btn.classList.remove('is-holding');
    clearTimers();
    if (!isReduced()) {
      const current = getComputedStyle(fill).transform;
      const retract = fill.animate(
        [{ transform: current && current !== 'none' ? current : 'scaleX(0)' }, { transform: 'scaleX(0)' }],
        { duration: 180, easing: 'ease-out', fill: 'none' },
      );
      retract.finished.then(() => { if (!destroyed && !confirmed) fill.style.transform = 'scaleX(0)'; }).catch(() => undefined);
    } else {
      fill.style.transform = 'scaleX(0)';
    }
  };

  const onPointerDown = (ev) => {
    if (ev.pointerType === 'mouse' && ev.button !== 0) return;
    startHold('pointer', ev.pointerId);
  };
  const onPointerUp = (ev) => {
    if (activeMode === 'pointer' && ev.pointerId === activePointerId) cancelHold('pointer');
  };
  const onPointerLeave = () => { if (activeMode === 'pointer') cancelHold('pointer'); };
  const onKeyDown = (ev) => {
    if (ev.repeat) return;
    if (ev.key === ' ' || ev.key === 'Enter') { ev.preventDefault(); startHold('key'); }
  };
  const onKeyUp = (ev) => {
    if (ev.key === ' ' || ev.key === 'Enter') cancelHold('key');
  };
  const onBlur = () => { cancelHold(null); };

  btn.addEventListener('pointerdown', onPointerDown);
  btn.addEventListener('pointerup', onPointerUp);
  btn.addEventListener('pointercancel', onPointerUp);
  btn.addEventListener('pointerleave', onPointerLeave);
  btn.addEventListener('keydown', onKeyDown);
  btn.addEventListener('keyup', onKeyUp);
  btn.addEventListener('blur', onBlur);

  return {
    start() { startHold('program'); },
    cancel() { cancelHold(null); },
    reset() {
      if (destroyed) return;
      clearTimers();
      activeMode = null;
      activePointerId = null;
      confirmed = false;
      btn.classList.remove('is-holding', 'is-confirmed');
      fill.style.transform = 'scaleX(0)';
    },
    isConfirmed: () => confirmed,
    destroy() {
      if (destroyed) return;
      destroyed = true;
      clearTimers();
      btn.removeEventListener('pointerdown', onPointerDown);
      btn.removeEventListener('pointerup', onPointerUp);
      btn.removeEventListener('pointercancel', onPointerUp);
      btn.removeEventListener('pointerleave', onPointerLeave);
      btn.removeEventListener('keydown', onKeyDown);
      btn.removeEventListener('keyup', onKeyUp);
      btn.removeEventListener('blur', onBlur);
      btn.classList.remove('htc-force', 'is-holding', 'is-confirmed');
      fill.style.transform = '';
    },
  };
}
```

## 出处

- 第四批备选（竞品常见长按确认交互），本站按通用做法自研实现，没有复制代码；支持指针与键盘空格/回车长按及中途取消回退
