如何实现点击切换section的open类并移除其他元素的该类?
解决方案
先修正HTML的ID问题
HTML里两个section重复使用了id="swup",ID在页面中必须唯一,建议修改为:
<main> <section class="left" id="section-left" > <img src="https://picsum.photos/200/300" alt=""> </section> <section class="right" id="section-right" > <img src="https://picsum.photos/200/400" alt=""> </section> </main>
修改JavaScript逻辑
核心问题是你没有先清空所有section的open类,就直接toggle当前元素的类。另外getElementsByTagName返回的是HTMLCollection(不是数组),不能直接用filter方法,必须先转成数组操作。
修改后的代码如下:
document.addEventListener("DOMContentLoaded", function() { // 直接把获取到的元素转成数组,避免重复转换 const sections = Array.from(document.getElementsByTagName("section")); sections.forEach(function(section) { section.addEventListener('click', function() { // 先移除所有section的open类,确保只有当前点击的会被选中 sections.forEach(sec => sec.classList.remove("open")); // 给当前点击的section添加open类 this.classList.add("open"); // 如果需要支持「点击已选中的section取消选中」,替换成下面的逻辑: // const isCurrentOpen = this.classList.contains("open"); // sections.forEach(sec => sec.classList.remove("open")); // if (!isCurrentOpen) this.classList.add("open"); }); }); });
补充说明
- 关于
filter的用法:如果你想用filter拿到当前元素之外的其他section,要基于转好的数组操作,比如:
这个逻辑和遍历所有section移除类的效果完全一致,只是写法不同。const otherSections = sections.filter(sec => sec !== this); otherSections.forEach(sec => sec.classList.remove("open"));
内容的提问来源于stack exchange,提问作者Aurore
相关产品推荐
相关产品推荐

