如何实现FAQ手风琴的双向切换功能?修复交互逻辑
FAQ手风琴组件:实现点击展开/关闭及单组显示功能
问题分析
当前代码已实现「同一时间仅显示一组问答」,但无法点击已展开的问题将其关闭。原因是点击事件中先移除了所有active类,随后直接调用toggle,导致原本展开的元素在移除类后又被重新添加,无法完成关闭操作。
解决方案
修改JavaScript逻辑:先记录当前点击元素是否处于激活状态,移除所有元素的active类后,仅当元素原本未激活时才添加active类;如果原本已激活,则保持关闭状态。
修改后的代码
HTML(无需改动)
<div class="text"> <h1>FAQ</h1> <ul> <li> <div class="question"> <h2>How many team members can I invite?</h2> </div> <p>You can invite up to 2 additional users on the Free plan. There is no limit on team members for the Premium plan. </p> </li> <li> <div class="question"> <h2>What is the maximum file upload size?</h2> </div> <p>No more than 2GB. All files in your account must fit your allotted storage space.</p> </li> <li> <div class="question"> <h2>How do I reset my password?</h2> </div> <p>Click “Forgot password” from the login page or “Change password” from your profile page. A reset link will be emailed to you.</p> </li> <li> <div class="question"> <h2>Can I cancel my subscription?</h2> </div> <p>Yes! Send us a message and we’ll process your request no questions asked.</p> </li> <li> <div class="question"> <h2>Do you provide additional support?</h2> </div> <p>Chat and email support is available 24/7. Phone lines are open during normal business hours.</p> </li> </ul> </div>
CSS(无需改动)
.text h1 { font-weight: 700; font-size: 2rem; margin-bottom: 20px; } ul { list-style: none; } ul>li { padding: 10px 10px 10px 0; border-bottom: 1px solid grey; } .question { margin-bottom: 10px; } ul li h2 { font-weight: 400; font-size: 1rem; cursor: pointer; transition: 0.1s; } ul li img { transition: 0.3s; } ul li h2:hover { color: red; font-weight: 700; } li p { font-weight: 400; height: 0; overflow: hidden; transition: 0.3s; } .active p { height: 40px; }
修改后的JavaScript
let allquestions = document.querySelectorAll("li"); allquestions.forEach(function (question) { question.addEventListener("click", function () { // 记录当前元素是否已激活 const isActive = this.classList.contains("active"); // 移除所有元素的active类 allquestions.forEach(function (element) { element.classList.remove("active"); }); // 仅当元素原本未激活时,添加active类 if (!isActive) { this.classList.add("active"); } }); });
逻辑说明
- 点击事件触发时,先判断当前元素是否拥有
active类,保存这个状态。 - 移除所有问答项的
active类,确保同一时间只有一组可能被激活。 - 如果当前元素原本未激活,则添加
active类展开内容;如果原本已激活,则不添加,实现关闭效果。
内容的提问来源于stack exchange,提问作者simokitkat
相关产品推荐
相关产品推荐

