点击展开某一章节时如何自动折叠其余所有章节
实现方案
你需要的这种点击展开一个章节、其余已展开章节自动折叠的交互叫**手风琴(Accordion)**效果,针对你现有的代码有两种实现方式:
方案1:纯CSS实现(无需JavaScript,改动最小,推荐)
你当前使用的type="checkbox"表单元素本身支持多选,替换为同name属性的type="radio"单选框,即可天然实现互斥选中效果:
修改HTML代码
- 将所有
.toggle-item的type属性从checkbox改为radio - 给所有
.toggle-item添加相同的name属性,例如name="resume-toggle" - 修正原有重复的
id="work"、id="work-item"问题(HTML规范要求id必须唯一,否则会影响label和表单的关联逻辑) - 仅给默认要展开的第一个选项添加
checked属性
修改后的核心HTML示例:
<div id="resume"> <section class="section"> <section class="work-section"> <section class="work-item"> <!-- 替换为radio,添加相同name属性 --> <input id="work-item-0" type="radio" name="resume-toggle" class="toggle-item" checked /> <label for="work-item-0"></label> <header> <div class="position">Joe</div> </header> <div class="item work-item-content"> <div class="summary"> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> </div> </div> </section> </section> <section class="work-section"> <section class="work-item"> <input id="work-item-1" type="radio" name="resume-toggle" class="toggle-item" /> <label for="work-item-1"></label> <header> <div class="position">Doe</div> </header> <div class="item work-item-content"> <div class="summary"> <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </p> </div> </div> </section> </section> </div>
调整CSS过渡逻辑
你现有CSS中height: auto无法触发平滑过渡,修改为max-height适配即可:
.toggle-item ~ .item { max-height: 0; opacity: 0; overflow: hidden; transition: all .5s linear; } .toggle-item:checked ~ .item { max-height: 2000px; /* 设置为比你最大内容高度更大的值即可 */ opacity: 1; }
方案2:保留checkbox逻辑,用JavaScript实现
如果你需要支持点击已展开的章节可以将其折叠(允许所有章节都处于收起状态),可以保留checkbox逻辑,添加少量JS实现互斥效果:
在</body>标签前添加如下代码:
const toggleList = document.querySelectorAll('.toggle-item'); toggleList.forEach(toggle => { toggle.addEventListener('change', function() { // 仅当前选项被选中时,取消其他选项的选中状态 if(this.checked) { toggleList.forEach(item => { if(item !== this) item.checked = false; }) } }) })
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

