# 步骤条切换（Animated step progress）

- 俗称：分步引导进度条；多步骤流程切换；步骤指示器连线推进；结账流程步骤条
- 用在：导航、按钮（工具和应用、品牌官网）
- 触发：点击
- 感觉：利落、科技感
- 版本：1，更新于 2026-11-17

## 原理

用一条左对齐缩放（transform-origin: left）的进度线代表已完成比例，切换步骤时按步骤序号算出目标 scaleX，交由 CSS transition 按设定耗时和缓动平滑推进，避免改 width 触发重排；节点同步切换 aria-current="step" 并支持左右方向键切换；减少动态时关闭过渡直接高亮对应步骤。

适合：多步表单、开通引导、下单结账、向导页，需要让用户清楚自己走到第几步以及还能点回前面修改时。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `duration` | 推进时长 | 400ms | 150–1000ms |
| `easing` | 缓动 | cubic-bezier(0.22, 1, 0.36, 1) | — |

## 质量要求

- 开启"减少动态"时：关闭连线和节点过渡，切换步骤时立即高亮对应节点并把进度线摆到位。
- 手机上：步骤标签保持单行或简短词组，步骤按钮可点区域高度不小于 44px，避免横向溢出。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

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

```text
请在我的项目里给导航加上「步骤条切换」（Animated step progress）效果：用一条左对齐缩放（transform-origin: left）的进度线代表已完成比例，切换步骤时按步骤序号算出目标 scaleX，交由 CSS transition 按设定耗时和缓动平滑推进，避免改 width 触发重排；节点同步切换 aria-current="step" 并支持左右方向键切换；减少动态时关闭过渡直接高亮对应步骤。
参数：推进时长 400ms，缓动 cubic-bezier(0.22, 1, 0.36, 1)。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/step-indicator.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<ol class="stp-bar" id="steps" aria-label="开通步骤">
  <span class="stp-track" aria-hidden="true"></span>
  <span class="stp-fill" aria-hidden="true"></span>
  <li class="stp-step is-active"><button type="button" class="stp-btn" aria-current="step"><span class="stp-dot">1</span><span class="stp-label">选效果</span></button></li>
  <li class="stp-step"><button type="button" class="stp-btn"><span class="stp-dot">2</span><span class="stp-label">改参数</span></button></li>
  <li class="stp-step"><button type="button" class="stp-btn"><span class="stp-dot">3</span><span class="stp-label">复制代码</span></button></li>
</ol>

<script type="module">
  import { stepIndicator } from './step-indicator.js';
  stepIndicator(document.getElementById('steps'), { step: 0 });
</script>
```

CSS：

```css
/* 步骤条切换（Animated step progress）样式，配合 step-indicator.js。 */
.stp-bar {
  position: relative;
  display: grid;
  grid-auto-flow: column;
  grid-auto-columns: 1fr;
  align-items: start;
  list-style: none;
  margin: 0;
  padding: 0;
}

.stp-track,
.stp-fill {
  position: absolute;
  top: 13px;
  left: var(--stp-inset, 16%);
  right: var(--stp-inset, 16%);
  height: 3px;
  border-radius: 999px;
  pointer-events: none;
}

.stp-track {
  background: color-mix(in srgb, currentColor 16%, transparent);
}

.stp-fill {
  background: var(--stp-color, currentColor);
  transform-origin: left center;
  transform: scaleX(0);
  transition: transform var(--stp-duration, 400ms) var(--stp-easing, cubic-bezier(0.22, 1, 0.36, 1));
}

.stp-step {
  position: relative;
  z-index: 1;
  display: grid;
  justify-items: center;
}

.stp-btn {
  display: grid;
  justify-items: center;
  gap: 6px;
  min-height: 44px;
  padding: 0 6px;
  border: 0;
  background: transparent;
  color: inherit;
  font: inherit;
  cursor: pointer;
}

.stp-dot {
  width: 28px;
  height: 28px;
  border-radius: 999px;
  display: grid;
  place-items: center;
  font-size: 12px;
  font-weight: 700;
  background: var(--stp-paper, #f4f3f0);
  border: 2px solid color-mix(in srgb, currentColor 26%, transparent);
  transition:
    background-color var(--stp-duration, 400ms) var(--stp-easing, cubic-bezier(0.22, 1, 0.36, 1)),
    border-color var(--stp-duration, 400ms) var(--stp-easing, cubic-bezier(0.22, 1, 0.36, 1)),
    color var(--stp-duration, 400ms) var(--stp-easing, cubic-bezier(0.22, 1, 0.36, 1));
}

.stp-label {
  font-size: 12px;
  opacity: 0.65;
  white-space: nowrap;
}

.stp-step.is-done .stp-dot,
.stp-step.is-active .stp-dot {
  border-color: var(--stp-color, currentColor);
  background: var(--stp-color, currentColor);
  color: var(--stp-paper, #ffffff);
}

.stp-step.is-active .stp-label,
.stp-step.is-done .stp-label {
  opacity: 1;
  font-weight: 700;
}

.stp-bar.stp-reduced .stp-fill,
.stp-bar.stp-reduced .stp-dot {
  transition: none;
}

@media (prefers-reduced-motion: reduce) {
  .stp-bar:not(.stp-force) .stp-fill,
  .stp-bar:not(.stp-force) .stp-dot {
    transition: none;
  }
}
```

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

```js
// 步骤条切换（Animated step progress）参考实现。
// 用法：容器为 <ol class="stp-bar">，含 .stp-fill 和若干 <li class="stp-step"><button class="stp-btn">...</button></li>。
// 调 const ctl = stepIndicator(root, { step: 0, duration: 400, easing: '...' }); 销毁调 ctl.destroy()。

export function stepIndicator(root, {
  step = 0,
  duration = 400,
  easing = 'cubic-bezier(0.22, 1, 0.36, 1)',
  ignoreReducedMotion = false,
} = {}) {
  if (!(root instanceof Element)) return null;
  const steps = [...root.querySelectorAll('.stp-step')];
  const fill = root.querySelector('.stp-fill');
  if (steps.length < 2 || !fill) return null;

  const buttons = steps.map((s) => s.querySelector('.stp-btn')).filter(Boolean);
  const dur = Number(duration) || 400;
  const easeStr = String(easing);
  const reduceQuery = typeof matchMedia === 'function' ? matchMedia('(prefers-reduced-motion: reduce)') : null;
  const clampIdx = (i) => Math.min(steps.length - 1, Math.max(0, Math.round(Number(i) || 0)));

  let currentIndex = clampIdx(step);
  let destroyed = false;

  root.classList.add('stp-bar');
  if (ignoreReducedMotion) root.classList.add('stp-force');
  root.style.setProperty('--stp-duration', `${dur}ms`);
  root.style.setProperty('--stp-easing', easeStr);
  root.style.setProperty('--stp-inset', `${(50 / steps.length).toFixed(2)}%`);

  const apply = (idx, immediate) => {
    if (destroyed) return;
    currentIndex = clampIdx(idx);
    const ratio = currentIndex / (steps.length - 1);
    const skip = immediate || Boolean(reduceQuery?.matches && !ignoreReducedMotion);
    if (skip) fill.style.transition = 'none';
    fill.style.transform = `scaleX(${ratio})`;
    steps.forEach((el, i) => {
      el.classList.toggle('is-done', i < currentIndex);
      el.classList.toggle('is-active', i === currentIndex);
      const btn = el.querySelector('.stp-btn');
      if (btn) {
        if (i === currentIndex) btn.setAttribute('aria-current', 'step');
        else btn.removeAttribute('aria-current');
      }
    });
    if (skip) {
      void fill.getBoundingClientRect();
      if (!(reduceQuery?.matches && !ignoreReducedMotion)) fill.style.transition = '';
    }
  };

  const go = (idx) => {
    if (destroyed) return;
    const prev = currentIndex;
    const next = clampIdx(idx);
    if (next === prev) return;
    apply(next, false);
    if (destroyed) return;
    root.dispatchEvent(new CustomEvent('stepchange', { bubbles: true, detail: { index: currentIndex, previous: prev } }));
  };

  const cleanups = [];
  buttons.forEach((btn, idx) => {
    const onClick = () => go(idx);
    const onKey = (ev) => {
      if (ev.key === 'ArrowRight' || ev.key === 'ArrowDown') {
        ev.preventDefault();
        const next = clampIdx(idx + 1);
        go(next);
        buttons[next]?.focus();
      } else if (ev.key === 'ArrowLeft' || ev.key === 'ArrowUp') {
        ev.preventDefault();
        const prev = clampIdx(idx - 1);
        go(prev);
        buttons[prev]?.focus();
      }
    };
    btn.addEventListener('click', onClick);
    btn.addEventListener('keydown', onKey);
    cleanups.push(() => {
      btn.removeEventListener('click', onClick);
      btn.removeEventListener('keydown', onKey);
    });
  });

  // 初始化定位不播过渡
  apply(currentIndex, true);

  return {
    go,
    next() { go(currentIndex + 1); },
    prev() { go(currentIndex - 1); },
    current() { return currentIndex; },
    destroy() {
      if (destroyed) return;
      destroyed = true;
      cleanups.forEach((fn) => fn());
      root.classList.remove('stp-force');
      root.style.removeProperty('--stp-duration');
      root.style.removeProperty('--stp-easing');
      root.style.removeProperty('--stp-inset');
      fill.style.transform = '';
      fill.style.transition = '';
      steps.forEach((el) => {
        el.classList.remove('is-done', 'is-active');
        el.querySelector('.stp-btn')?.removeAttribute('aria-current');
      });
    },
  };
}
```

## 出处

- 本站自研：基于 transform: scaleX 的步骤进度条与键盘左右导航控制
