Web前端技术 · 第2课14 / 16 | 编码:L02-90
进阶观察 · 从本课知识向前一步

只写 HTML,也能做互斥展开

连续打开两个活动说明,观察前一个是否自动收起。这里没有负责展开的 JavaScript。

先看效果

单独打开演示

01 · 容器与摘要

<details><summary>唱腔赏析</summary>说明内容</details>

details 保存可展开的内容;summary 是始终可见的标题入口。

02 · 同名成为一组

<details name="events">…</details>

多个 details 使用同一个 name,支持该特性的浏览器会保证这一组最多展开一个。

03 · 开关不等于页面跳转

<details name="events" open>…</details>

open 指定初始展开;它不是超链接,不需要跳到另一个文件。

思考

把第二项的 name 改成 other 后,打开它还会关闭第一项吗?给第一项设置 id="events" 能替代 name 吗?

展开参考分析

不同 name 属于不同组,可以同时展开。id 用于唯一标识,不负责这种分组;把 id 写成同一个值也不会建立互斥关系。

现代 HTML:details 的 name 分组比基础展开功能更新;旧浏览器可能允许多项同时展开,内容仍可阅读。

完整源码:展开、修改与运行
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>只写 HTML,也能做互斥展开</title>
  <style>
body { margin:16px; color:#183347; background:white; font:20px/1.5 "Times New Roman",SimSun,serif; }
h1,h2 { font-family:"Times New Roman",SimHei,sans-serif; }
button,input,select { font:inherit; max-width:100%; }
button { margin:4px 0; cursor:pointer; }
pre { white-space:pre-wrap; overflow-wrap:anywhere; font:18px/1.5 Consolas,SimSun,monospace; }
:focus-visible { outline:3px solid #b56220; outline-offset:3px; }
details { border-bottom:2px solid #bfd9d3; padding:16px; }
summary { cursor:pointer; font-weight:bold; }
  </style>
</head>
<body>
<details name="events"><summary>唱腔赏析</summary><p>了解黄梅戏的唱腔特点。</p></details>
<details name="events"><summary>服饰介绍</summary><p>观察角色服饰与舞台表达。</p></details>
<details name="events"><summary>交流环节</summary><p>提出问题并分享观察。</p></details>
</body>
</html>