# 搜索展开（Expanding search bar）

- 俗称：搜索图标展开成输入框；点击放大镜长出搜索框；导航栏伸缩搜索输入框；搜索按钮平滑拉长成输入框
- 用在：导航、按钮（文档站、个人网站、作品集、工具站）
- 触发：点击
- 感觉：利落、柔和
- 版本：1，更新于 2026-12-01

## 原理

语义化的 <form role="search"> 内放触发按钮与 <input type="search">，无脚本时默认展开保证随时可搜；脚本挂载后设为收起宽度，点击时先切换状态并量取起止宽，再用 WAAPI 对容器 width 做动画并聚焦输入框；监听 Esc（检查 !isComposing 避免打断中文输入法）与空内容失焦收起；减少动态时直接切换宽度。

适合：文档站、作品集、工具站顶部导航：平常只占一个图标位置省出空间，点开时顺滑展开输入，按 Esc 或失焦为空时收回。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `duration` | 展开时长 | 320ms | 150–700ms |
| `expandedWidth` | 展开宽度 | 200px | 140–240px |
| `easing` | 缓动 | cubic-bezier(0.22, 1, 0.36, 1) | — |

## 质量要求

- 开启"减少动态"时：跳过宽度过渡动画，点击按钮后直接切换为完整输入框或收起图标。
- 手机上：窄屏建议把展开宽度设在容器可用宽度的 60%–85%，或配合顶栏隐藏其余次要按钮。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

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

```text
请在我的项目里给导航加上「搜索展开」（Expanding search bar）效果：语义化的 <form role="search"> 内放触发按钮与 <input type="search">，无脚本时默认展开保证随时可搜；脚本挂载后设为收起宽度，点击时先切换状态并量取起止宽，再用 WAAPI 对容器 width 做动画并聚焦输入框；监听 Esc（检查 !isComposing 避免打断中文输入法）与空内容失焦收起；减少动态时直接切换宽度。
参数：展开时长 320ms，展开宽度 200px，缓动 cubic-bezier(0.22, 1, 0.36, 1)。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/expanding-search.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<!-- 搜索展开：无脚本默认展开可用，脚本挂载后先收成图标，点放大镜拉长成输入框 -->
<form class="es-box" role="search" data-expanded="true" onsubmit="return false" style="border: 1px solid #dddcd6; background: #fff;">
  <button type="button" class="es-toggle" aria-label="搜索">
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">
      <circle cx="7" cy="7" r="4.5" />
      <path d="M10.4 10.4L14 14" stroke-linecap="round" />
    </svg>
  </button>
  <input type="search" class="es-input" placeholder="搜索文档…" aria-label="搜索文档" />
</form>
<script type="module">
  import { expandingSearch } from './expanding-search.js';
  expandingSearch(document.querySelector('.es-box'), { duration: 320, expandedWidth: 200 });
</script>
```

CSS：

```css
/* 搜索展开（Expanding search bar）：配合 expanding-search.js。
   无脚本时保持 data-expanded="true" 完整可见；脚本接手后默认收起为圆形图标按钮。 */
:where(.es-box) {
  --es-duration: 320ms;
  --es-expanded-width: 200px;
  --es-easing: cubic-bezier(0.22, 1, 0.36, 1);
  --es-collapsed-width: 36px;
  box-sizing: border-box;
  display: inline-flex;
  align-items: center;
  height: 36px;
  border-radius: 999px;
  overflow: hidden;
  vertical-align: middle;
}

.es-box[data-expanded="false"] {
  width: var(--es-collapsed-width, 36px);
}

.es-box[data-expanded="true"] {
  width: var(--es-expanded-width, 200px);
}

.es-toggle {
  flex: none;
  display: inline-grid;
  place-items: center;
  width: 34px;
  height: 34px;
  padding: 0;
  border: 0;
  background: transparent;
  color: inherit;
  cursor: pointer;
}

.es-input {
  flex: 1;
  min-width: 0;
  border: 0;
  background: transparent;
  color: inherit;
  font: inherit;
  outline: none;
}

.es-box[data-expanded="false"] .es-input {
  width: 0;
  padding: 0;
  opacity: 0;
  pointer-events: none;
}

.es-box[data-expanded="true"] .es-input {
  padding: 0 12px 0 2px;
  opacity: 1;
  pointer-events: auto;
}

.es-clear {
  flex: none;
  display: inline-grid;
  place-items: center;
  width: 26px;
  height: 26px;
  margin-right: 4px;
  border: 0;
  border-radius: 50%;
  background: transparent;
  color: inherit;
  cursor: pointer;
}

.es-box[data-expanded="false"] .es-clear {
  display: none;
}
```

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

```js
// 搜索展开（Expanding search bar）· 原生 JS，不依赖任何库。
// 用法：<form class="es-box" role="search" data-expanded="true"> 内含 .es-toggle 按钮与 .es-input 输入框，
// 调用 expandingSearch(box, { duration: 320, expandedWidth: 200, easing: 'cubic-bezier(0.22, 1, 0.36, 1)' })。
// 返回 { setExpanded(next, opts), toggle(), isExpanded(), destroy() }。

/**
 * @param {HTMLElement} root
 * @param {{ duration?: number, expandedWidth?: number, easing?: string, expanded?: boolean, ignoreReducedMotion?: boolean }} [options]
 */
export function expandingSearch(root, {
  duration = 320,
  expandedWidth = 200,
  easing = 'cubic-bezier(0.22, 1, 0.36, 1)',
  expanded = false,
  ignoreReducedMotion = false,
} = {}) {
  if (!(root instanceof Element)) return null;
  const toggleBtn = root.querySelector('.es-toggle');
  const input = root.querySelector('.es-input');
  const clearBtn = root.querySelector('.es-clear');
  if (!toggleBtn || !input) return null;

  let destroyed = false;
  let isOpen = Boolean(expanded);
  let activeAnim = null;
  const dur = Math.max(0, Number(duration) || 320);
  const targetWidth = Math.max(80, Number(expandedWidth) || 200);
  const easeStr = String(easing);
  const reduceQuery = typeof matchMedia === 'function' ? matchMedia('(prefers-reduced-motion: reduce)') : null;
  const isReduced = () => Boolean(reduceQuery?.matches && !ignoreReducedMotion);

  root.classList.add('es-box');
  root.style.setProperty('--es-duration', `${dur}ms`);
  root.style.setProperty('--es-expanded-width', `${targetWidth}px`);
  root.style.setProperty('--es-easing', easeStr);

  const syncAttr = () => {
    root.dataset.expanded = String(isOpen);
    toggleBtn.setAttribute('aria-expanded', String(isOpen));
  };

  syncAttr();

  const setExpanded = (next, { animate = true, focus = false } = {}) => {
    if (destroyed) return;
    const target = Boolean(next);
    if (target === isOpen) {
      if (focus && target && input instanceof HTMLElement) input.focus();
      return;
    }

    if (activeAnim) {
      activeAnim.cancel();
      activeAnim = null;
    }

    const fromWidth = root.getBoundingClientRect().width;
    isOpen = target;
    syncAttr();
    const toWidth = root.getBoundingClientRect().width;

    if (animate && !isReduced() && fromWidth > 0 && toWidth > 0 && Math.abs(fromWidth - toWidth) > 0.5) {
      activeAnim = root.animate(
        [{ width: `${fromWidth}px` }, { width: `${toWidth}px` }],
        { duration: dur, easing: easeStr, fill: 'none' },
      );
      activeAnim.finished.then(() => {
        if (!destroyed) activeAnim = null;
      }).catch(() => undefined);
    }

    if (focus) {
      if (isOpen && input instanceof HTMLElement) input.focus();
      else if (!isOpen && toggleBtn instanceof HTMLElement) toggleBtn.focus();
    }

    root.dispatchEvent(new CustomEvent('searchtoggle', { bubbles: true, detail: { expanded: isOpen } }));
  };

  const onToggle = () => {
    if (isOpen && input instanceof HTMLInputElement && input.value.trim()) {
      root.dispatchEvent(new CustomEvent('searchsubmit', { bubbles: true, detail: { query: input.value.trim() } }));
      return;
    }
    setExpanded(!isOpen, { focus: !isOpen });
  };

  const onClear = () => {
    if (input instanceof HTMLInputElement) {
      input.value = '';
      input.focus();
    }
  };

  const onKeyDown = (ev) => {
    if (ev.key === 'Escape' && !ev.isComposing && isOpen) {
      ev.preventDefault();
      setExpanded(false, { focus: true });
    }
  };

  const onFocusOut = (ev) => {
    const related = ev.relatedTarget;
    if (related instanceof Node && root.contains(related)) return;
    if (isOpen && input instanceof HTMLInputElement && !input.value.trim()) {
      setExpanded(false);
    }
  };

  toggleBtn.addEventListener('click', onToggle);
  if (clearBtn) clearBtn.addEventListener('click', onClear);
  root.addEventListener('keydown', onKeyDown);
  root.addEventListener('focusout', onFocusOut);

  return {
    setExpanded,
    toggle() { setExpanded(!isOpen, { focus: !isOpen }); },
    isExpanded: () => isOpen,
    destroy() {
      if (destroyed) return;
      destroyed = true;
      if (activeAnim) {
        activeAnim.cancel();
        activeAnim = null;
      }
      toggleBtn.removeEventListener('click', onToggle);
      if (clearBtn) clearBtn.removeEventListener('click', onClear);
      root.removeEventListener('keydown', onKeyDown);
      root.removeEventListener('focusout', onFocusOut);
      root.style.removeProperty('--es-duration');
      root.style.removeProperty('--es-expanded-width');
      root.style.removeProperty('--es-easing');
      toggleBtn.removeAttribute('aria-expanded');
    },
  };
}
```

## 出处

- 本站原创实现：使用 WAAPI 测量起止宽度的自适应伸缩搜索框，支持 IME 防误触与无脚本默认展开，未使用第三方代码
