如何用jQuery实现Q&A区域仅同时展开一个折叠面板?
实现单展开FAQ盒子的解决方案
当然可以实现这个需求!我们只需要在现有代码基础上添加逻辑,确保每次只有一个FAQ盒子处于展开状态。下面是修改后的完整代码,以及关键改动的解释:
修改后的完整代码
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <div class="faqSection"> <div class="faqSectionSub"> <h4 class="faqOuter">Trial One Bar</h4> <div class="faqInner"> <p>Alienum phaedrum torquatos nec eu, vis detraxit periculis ex, nihil expetendis in mei.</p> </div> </div> <div class="faqSectionSub"> <h4 class="faqOuter">Trial One Bar</h4> <div class="faqInner"> <p>Alienum phaedrum torquatos nec eu, vis detraxit periculis ex, nihil expetendis in mei.</p> </div> </div> <div class="faqSectionSub"> <h4 class="faqOuter">Trial One Bar</h4> <div class="faqInner"> <p>Alienum phaedrum torquatos nec eu, vis detraxit periculis ex, nihil expetendis in mei.</p> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script> $(document).ready(function() { $(".faqOuter").click(function() { // 获取当前点击盒子的父容器 const currentParent = $(this).parent(); // 判断当前盒子是否已展开 const isExpanded = currentParent.hasClass('faqOuter-change'); // 关闭所有其他已展开的FAQ盒子 $('.faqSectionSub').not(currentParent).each(function() { if ($(this).hasClass('faqOuter-change')) { $(this).removeClass('faqOuter-change'); $(this).find('.faqInner').slideUp(500, 'swing'); $(this).animate({ height: '75' }, 600, 'swing'); } }); // 处理当前点击的盒子 if (!isExpanded) { $(this).addClass('faqOuter-change'); currentParent.find('.faqInner').slideDown(500, 'swing'); currentParent.animate({ height: '225' }, 500, 'swing'); } else { $(this).removeClass('faqOuter-change'); currentParent.find('.faqInner').slideUp(500, 'swing'); currentParent.animate({ height: '75' }, 600, 'swing'); } }); }); </script>
关键改动说明
- 修正语法错误:原代码中选择器的
\.是多余的转义符,以及animate方法的参数位置错误(原代码把动画时长写在了括号外),这些都已修复。 - 添加全局关闭逻辑:使用
$('.faqSectionSub').not(currentParent)选中除当前盒子外的所有FAQ容器,遍历并关闭已展开的盒子,确保同时只有一个盒子展开。 - 明确状态控制:将原有的
toggleClass拆分为addClass和removeClass,配合状态判断,让逻辑更清晰,避免和其他盒子的操作产生冲突。
这样修改后,你点击任意一个FAQ盒子时,其他已展开的盒子会自动收起,实现了一次仅显示一个展开状态盒子的需求。
内容的提问来源于stack exchange,提问作者RePotato
相关产品推荐
相关产品推荐

