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

如何实现点击箭头按钮时切换对应摘要的开/关显隐效果

FAQ折叠交互问题修复

核心错误点

  • ID重复使用违反HTML规范:页面中id属性必须全局唯一,你给所有箭头、所有摘要段落都设置了相同的id="uparrow"、id="para",会导致DOM选择匹配异常。需要把重复ID替换为通用类名。
  • 事件绑定目标错误:document.querySelectorAll返回的是元素节点列表,你在循环中直接对整个列表arrow调用addEventListener是无效的,必须对当前遍历到的单个元素arrow[i]绑定事件。
  • 缺少必要基础样式:用opacity+max-height实现折叠时,需要给摘要元素加overflow: hidden避免内容在高度为0时溢出,加过渡属性可以实现平滑展开/收起效果。

修复后完整代码

HTML结构(替换重复ID为类名)

<section>
    <div class="content">
        <h3>How does it work?</h3>
        <i class="fa fa-angle-up arrow"></i>
    </div>
    <p class="summary">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Sequi provident ut sed
        eaque earum
        commodi consectetur iandae magnam nostrum gendi veniam voluptate beatae. Non soluta
        reprehenderit quas dicta?</p>
</section>
<section>
    <div class="content">
        <h3>其他问题标题</h3>
        <i class="fa fa-angle-up arrow"></i>
    </div>
    <p class="summary">对应问题的摘要内容</p>
</section>
<!-- 剩余折叠项按相同结构编写即可 -->

补充CSS样式

/* 摘要默认隐藏状态 */
.summary {
    opacity: 0;
    max-height: 0;
    overflow: hidden;
    margin: 0;
    padding: 0 1rem;
    /* 平滑动画过渡 */
    transition: all 0.3s ease;
}
/* 箭头样式 */
.arrow {
    cursor: pointer;
    transition: transform 0.3s ease;
}

修复后JS逻辑

// 改用类选择器匹配所有对应元素
const arrow = document.querySelectorAll('.arrow');
const para = document.querySelectorAll('.summary');

for(let i = 0; i < arrow.length; i++){
    // 给单个箭头元素绑定点击事件
    arrow[i].addEventListener('click', () => {
        closeAll();
        openQuest(i);
    })
}

function openQuest(i){
    para[i].style.opacity = '1';
    para[i].style.maxHeight = '10rem';
    arrow[i].style.transform = 'rotateX(180deg)';
}

function closeAll(){
    // 直接遍历箭头元素列表即可,无需依赖content长度
    for(let i = 0; i < arrow.length; i++){
        arrow[i].style.transform = 'rotateX(0deg)';
        para[i].style.maxHeight = '0rem';
        para[i].style.opacity = '0';
    }
}

修复后点击任意箭头,会先关闭所有展开的项,再打开当前点击对应的摘要,完全符合预期交互效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 13:48:14