中文
常见问题
你平时做什么?

写代码,也写文章,最近在做一个动效网站。

可以找你合作吗?

可以,发邮件给我,一两天内回。

网站是用什么做的?

Astro 加一点原生 JS,动效自己写。

Click & feedback · Vanilla JS + CSS

Smooth accordion

平滑折叠展开

Expand and collapse content at its natural height.

Also searched as: 点标题下面的内容展开,再点收起来, 常见问题点开看答案, 经历一条条点开看详情, 内容平滑地展开收起,不是一下子冒出来

AI Markdown (.md)
Placement
Article
Mood
Crisp, Soft
Trigger
点击
Site types
个人网站, 博客, 作品集

How it works & accessibility

Measure the content height and animate between zero and that height, returning to automatic height after expansion.

Best for: Article (点击).

Reduced motion: 直接展开、收起,不做高度动画;箭头直接换方向

Mobile & touch: 和桌面一样,手指点标题开合;标题行留够高度(至少 44px)好点

Key parameters

ParameterKeyDefaultRangeNotes
时长duration300ms——
缓动easingease-in-out——

Ready-to-paste AI prompt

Add “Smooth accordion” to the article in my project: Measure the content height and animate between zero and that height, returning to automatic height after expansion.
Parameters: duration: 300ms, easing: ease-in-out.
Preserve existing content and layout. Respect prefers-reduced-motion by showing the final state. Content must remain visible if JavaScript fails or is disabled.
Reference: https://donglang.linter.top/effects/accordion.md (canonical specification and reference code).

Dependency-free reference code

CSS
/* 平滑折叠展开(Smooth accordion)的样式,配合 accordion.js。每一项是一个原生的 <details>,加 class="acc"。
   改写自 Animation Handbook 的 Accordion Open/Close(MIT License,Copyright (c) 2026 Matin Monshizadeh)。
   - details 用 display: flow-root(自己成为一个独立的排版块):里面段落的上下外边距留在 details 里面、不和外面的合并,
     开着的高度量得准,动完不会跳一下。
   - 标题右边的小箭头:summary 里放 <span class="acc-arrow" aria-hidden="true"></span>,开着时转过来朝上。
     有脚本时看 is-open(一按就转,关的时候不等收完);没有脚本时看 [open]。浏览器自带的小三角去掉了。
   - 时长和缓动写在 --acc-duration、--acc-easing 上,脚本会按参数改成和高度动画一样的。
   - 开启"减少动态"时:箭头直接换方向,不转。 */
.acc {
  --acc-duration: 300ms;
  --acc-easing: ease-in-out;
  display: flow-root;
}
.acc > summary {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1em;
  cursor: pointer;
  list-style: none;
}
.acc > summary::-webkit-details-marker { display: none; }
.acc-arrow {
  flex: none;
  width: 0.5em;
  height: 0.5em;
  border-right: 2px solid currentColor;
  border-bottom: 2px solid currentColor;
  rotate: 45deg;
  translate: 0 -25%;
  transition: rotate var(--acc-duration) var(--acc-easing), translate var(--acc-duration) var(--acc-easing);
}
.acc:not(.acc-js)[open] .acc-arrow,
.acc.is-open .acc-arrow {
  rotate: 225deg;
  translate: 0 25%;
}
@media (prefers-reduced-motion: reduce) {
  .acc-arrow { transition: none; }
}
JavaScript
// 平滑折叠展开(Smooth accordion)· 原生 JS,不依赖任何库。用原生的 <details>:没有脚本时照样点得开(浏览器自己开合,只是没有动画),
// 键盘(回车、空格)、读屏、页面里搜文字时自动展开,都是浏览器自带的;脚本只负责让高度平滑地变。
// 做法改写自 Animation Handbook 的 Accordion Open/Close(MIT License,Copyright (c) 2026 Matin Monshizadeh):
// 量出内容真正的高度、让高度在两个真实值之间走(不用 max-height 设个大数,那样缓动会先花在用不上的那一截上),默认时长和缓动来自它。
// 本站改成:动的是整个 details 的高度(标题加内容),开的时候先把 open 打开、量出开着的高度,从关着的高度长到它;
// 关的时候先从开着的高度缩到关着的高度,缩完才把 open 关上(关上以后内容就不显示了,所以要最后关)。
// items 是一个或一组 <details>(配合 accordion.css:它让 details 自己成为一个独立的排版块,里面段落的上下外边距不会"漏"出去,
// 高度量得准、动完不跳)。正在开合的时候又点:从此刻的高度掉头,不会先跳回去。
// 动的那一会儿 details 加 overflow: hidden、box-sizing: border-box(高度按整个框算,details 有 padding、边框也不跳),动完还原成它原来的;
// 标题上的小箭头由 CSS 按 is-open 转过来(关的时候一按就转回去,不等收完)。标题里放了链接、按钮的,点它们照原样(不开合)。
// 动的那一会儿里面的内容变高(图片晚加载、改了窗口大小):这一下可能先被裁住、结尾跳一下,动完不留写死的高度,马上按真实的高度排。
// 要一次只开一个:别用 details 的 name 属性(浏览器会直接把别的关掉、没有动画),自己在开一个时把别的也调一次 close。
// 返回 { open(details), close(details), destroy() }。开启"减少动态"时:直接开合,不做高度动画。ignoreReducedMotion 只给演示用。
/**
 * @param {HTMLDetailsElement | Iterable<HTMLDetailsElement>} items
 * @param {{ duration?: number, easing?: string, ignoreReducedMotion?: boolean }} [options]
 */
export function accordion(items, {
  duration = 300,
  easing = 'ease-in-out',
  ignoreReducedMotion = false,
} = {}) {
  const reduce = !ignoreReducedMotion && matchMedia('(prefers-reduced-motion: reduce)').matches;
  const list = items instanceof Element ? [items] : [...items];
  const moving = new WeakMap(); // details → 正在播的高度动画
  const saved = new WeakMap(); // details → 动之前它自己行内写的 overflow、box-sizing(动完还原)
  const restore = (el) => {
    if (!saved.has(el)) return;
    [el.style.overflow, el.style.boxSizing] = saved.get(el);
    saved.delete(el);
  };

  // 从 from 高度动到 to 高度;播完(或者被掉头取消)以后的收尾由调用的人做。
  // 量的高度是整个框(包括 padding 和边框),动的时候按 border-box 算:details 有 padding、边框时开头结尾不跳
  const glide = (el, from, to) => {
    moving.get(el)?.cancel();
    if (!saved.has(el)) saved.set(el, [el.style.overflow, el.style.boxSizing]);
    el.style.overflow = 'hidden';
    el.style.boxSizing = 'border-box';
    const anim = el.animate([{ height: `${from}px` }, { height: `${to}px` }], { duration, easing });
    moving.set(el, anim);
    return anim.finished.then(() => true, () => false).then((done) => {
      if (moving.get(el) === anim) {
        moving.delete(el);
        restore(el);
      }
      return done;
    });
  };
  // 此刻在画面上的高度(正在动的算上动画)
  const now = (el) => el.getBoundingClientRect().height;

  const open = (el) => {
    el.classList.add('is-open');
    if (reduce) { el.open = true; return Promise.resolve(true); }
    const from = now(el);
    el.open = true;
    moving.get(el)?.cancel(); // 量开着的高度时不能带着正在播的动画
    const to = el.offsetHeight;
    return glide(el, from, to);
  };
  const close = (el) => {
    el.classList.remove('is-open');
    if (reduce) { el.open = false; return Promise.resolve(true); }
    const from = now(el);
    moving.get(el)?.cancel();
    el.open = false;
    const to = el.offsetHeight; // 关着的高度:只剩标题
    el.open = true; // 收的时候内容还要看得见,收完再关
    return glide(el, from, to).then((done) => {
      if (done) el.open = false;
      return done;
    });
  };

  // 点标题(鼠标、手指、回车、空格都会触发 click):不让浏览器直接开合,改成自己动。
  // 点的是标题里的链接、按钮、输入框:照原样(浏览器自己也不开合,链接照常打开)
  const onClick = (e) => {
    const el = e.currentTarget.parentElement;
    const inner = e.target.closest('a[href], button, input, select, textarea, label');
    if (e.defaultPrevented || (inner && e.currentTarget.contains(inner))) return;
    e.preventDefault();
    (el.classList.contains('is-open') ? close : open)(el);
  };
  // 别的原因开合(页面里搜到了里面的字、脚本直接改 open):箭头跟上
  const onToggle = (e) => {
    const el = e.currentTarget;
    if (!moving.has(el)) el.classList.toggle('is-open', el.open);
  };
  const summaries = list.map((el) => {
    // acc-js:箭头改看 is-open;时长、缓动写到 CSS 变量上,箭头和高度一起动
    el.classList.add('acc-js');
    el.style.setProperty('--acc-duration', `${duration}ms`);
    el.style.setProperty('--acc-easing', easing);
    el.classList.toggle('is-open', el.open);
    const summary = el.querySelector(':scope > summary');
    summary?.addEventListener('click', onClick);
    el.addEventListener('toggle', onToggle);
    return summary;
  });

  return {
    open,
    close,
    destroy() {
      list.forEach((el, i) => {
        summaries[i]?.removeEventListener('click', onClick);
        el.removeEventListener('toggle', onToggle);
        moving.get(el)?.cancel();
        moving.delete(el);
        restore(el);
        el.style.removeProperty('--acc-duration');
        el.style.removeProperty('--acc-easing');
        el.classList.remove('is-open', 'acc-js');
      });
    },
  };
}
HTML
<!-- 平滑折叠展开:每一项是一个原生的 <details>,加 class="acc"。没有脚本时照样点得开(只是没有动画) -->
<section aria-labelledby="faq-title">
  <h2 id="faq-title">常见问题</h2>
  <details class="acc">
    <summary>你平时做什么?<span class="acc-arrow" aria-hidden="true"></span></summary>
    <p>写代码,也写文章……</p>
  </details>
  <details class="acc">
    <summary>可以找你合作吗?<span class="acc-arrow" aria-hidden="true"></span></summary>
    <p>可以,发邮件给我……</p>
  </details>
</section>
<script type="module">
  import { accordion } from './accordion.js';
  accordion(document.querySelectorAll('details.acc'));
</script>

More in Click & feedback

Browse all 86 effects →

Shown once per release · Always available in changelog