You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

我的HTML/CSS collapsible组件无法正常工作怎么办?

折叠模块点击无法展开的问题排查与解决

我参照示例代码制作网页折叠模块,但点击「current」按钮时,对应的折叠div无法展开。已确认button标签与折叠区域紧邻,通过浏览器检查工具发现,点击按钮时content.style.display属性未被正确设置,但手动修改该属性可达到预期效果。尝试用this.parentNode.nextElementSibling替代this.nextElementSibling,问题依旧。想问script标签的位置会影响功能吗?

我的代码片段:

HTML代码

<button type="button" class="collapsible">current</button>
<div class="content">
        <p>Lorem ipsum...</p>
</div>

CSS代码

.collapsible {
      background-color: #eee;
      color: #444;
      cursor: pointer;
      padding: 18px;
      width: 100%;
      border: none;
      text-align: left;
      outline: none;
      font-size: 15px;
}
.content {
      padding: 0 18px;
      overflow: hidden;
      background-color: #f1f1f1;
}
.active, .collapsible:hover {
      background-color: #ccc;
}

JS代码

const coll = document.getElementsByClassName("collapsible");
let i;

for (i = 0; i < coll.length; i++) {
   coll[i].addEventListener("click", function() {
        this.classList.toggle("active");
        let content = this.nextElementSibling;
        if (content.style.display === "block") {
                 content.style.display = "none";
        } else {
                 content.style.display = "block";
        }
  });
}

问题解决:

  1. script标签位置是核心原因
    如果script标签放在<head>里或者DOM元素之前,JS执行时页面还没加载完.collapsible按钮,导致事件监听没绑定成功。解决方式二选一:

    • 把script标签移到</body>标签之前,确保DOM完全加载后再执行JS;
    • 用DOMContentLoaded事件包裹JS代码,确保DOM加载完成后再初始化:
      document.addEventListener('DOMContentLoaded', function() {
        const coll = document.getElementsByClassName("collapsible");
        let i;
      
        for (i = 0; i < coll.length; i++) {
          coll[i].addEventListener("click", function() {
            this.classList.toggle("active");
            let content = this.nextElementSibling;
            if (content.style.display === "block") {
              content.style.display = "none";
            } else {
              content.style.display = "block";
            }
          });
        }
      });
      
  2. 优化默认折叠状态
    当前CSS里.content默认是展开的,若要默认折叠,给.content添加display: none:

.content {
  padding: 0 18px;
  overflow: hidden;
  background-color: #f1f1f1;
  display: none; /* 新增此行实现默认折叠 */
}

内容的提问来源于stack exchange,提问作者cillianreilly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:20:32