EN
文档
点击与反馈 · 原生 JS + CSS

搜索展开

Expanding search bar

点击搜索图标按钮时,图标平滑拉长成完整输入框并自动聚焦,收起时缩回图标按钮

常见大白话搜法:搜索图标展开成输入框、点击放大镜长出搜索框、导航栏伸缩搜索输入框、搜索按钮平滑拉长成输入框

AI 专用 Markdown (.md)
适用位置
导航、按钮
气质感觉
利落、柔和
触发方式
点击
适合网站
文档站、个人网站、作品集、工具站

实现原理与无障碍底线

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

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

减少动态(prefers-reduced-motion):跳过宽度过渡动画,点击按钮后直接切换为完整输入框或收起图标

移动端与触屏:窄屏建议把展开宽度设在容器可用宽度的 60%–85%,或配合顶栏隐藏其余次要按钮

关键可调参数

参数键名默认值建议范围说明
展开时长duration320ms——
展开宽度expandedWidth200px——
缓动easingcubic-bezier(0.22, 1, 0.36, 1)——

可直接复制给 AI(Cursor / Claude / v0)的提示词

请在我的项目里给导航加上「搜索展开」(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(原理、参数和参考代码)

原生无依赖参考代码

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;
}
JavaScript
// 搜索展开(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');
    },
  };
}
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>

同属「点击与反馈」的其他动效

查看全部 86 个动效 →

本次更新仅弹窗提醒一次 · 可随时在历史公告回看