← 中文资源

简体中文版本

details name 属性排他手风琴

同名 name 把多个 details 编成一组:展开一个自动收起其余,规范在 open 属性变更时强制排他,纯 HTML 即得手风琴,无需任何 JS。

阅读英文原文

实现说明

核心工作在嵌套循环里完成:外层 for (const title of ['Plan', 'Build', 'Ship']),内层 for (const panel of panels)。 panels、first 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 浏览器才是这里的运行环境:document 在 Node 里拿不到。
  • 演示输出是带标签的(grouped panels:、first panel open:),每个操作都会留下自己的一行标注。

常见问题

「details name 属性排他手风琴」能在裸 Node.js 里跑吗?

不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。

核心语句

setTimeout(() => {
  for (const panel of panels) {
    console.log(panel.querySelector('summary').textContent, 'open:', panel.open);
  }
}, 0);

代码示例

// <details name> groups panels into an exclusive accordion: opening one
// panel closes the others in the same group, with zero JavaScript
for (const title of ['Plan', 'Build', 'Ship']) {
  const panel = document.createElement('details');
  panel.name = 'release-phase';
  const summary = document.createElement('summary');
  summary.textContent = title;
  panel.append(summary, title + ' phase steps');
  document.body.append(panel);
}

const panels = document.querySelectorAll('details[name="release-phase"]');
console.log('grouped panels:', panels.length);

const first = panels[0];
first.open = true;
console.log('first panel open:', first.open);

// setting open on the second panel closes the first one automatically:
// the spec runs exclusivity on the open attribute change itself
panels[1].open = true;
setTimeout(() => {
  for (const panel of panels) {
    console.log(panel.querySelector('summary').textContent, 'open:', panel.open);
  }
}, 0);