Bootstrap 4手风琴点击标签滚动至对应区域的问题及解决需求
解决方案:适配所有手风琴标签的滚动效果
你的问题根源在于原代码没有区分每个点击标签对应的具体折叠区域——直接使用$('.sections')会选中所有带这个类的元素,最终只会滚动到第一个匹配的区域。下面是针对所有标签生效的jQuery方案,结合Bootstrap折叠组件的官方事件来实现更可靠的滚动:
修改后的jQuery代码
$('.toggling-tabs').on('click', function () { // 1. 获取当前点击标签对应的目标折叠区域ID(从data-target属性提取) const targetCollapseId = $(this).find('[data-toggle="collapse"]').data('target'); // 2. 定位到对应的折叠区域元素 const targetSection = $(targetCollapseId); // 3. 监听Bootstrap折叠完成事件,确保滚动在动画结束后触发 // 使用.one()避免重复绑定事件,防止多次点击时重复滚动 targetSection.one('shown.bs.collapse', function() { $('html, body').animate({ scrollTop: targetSection.offset().top }, 'slow'); }); });
代码详解
- 关联标签与目标区域:通过
$(this).find('[data-toggle="collapse"]')找到当前点击标签内的折叠触发元素,提取它的data-target值,这个值正好是对应折叠区域的ID,从而精准定位到要滚动到的区域。 - 利用Bootstrap折叠事件:使用
shown.bs.collapse事件(折叠区域完全展开后触发)来触发滚动,比监听collapsing类更可靠——因为Bootstrap的折叠动画有固定的时序,等待动画完成后滚动体验更流畅。 - 避免重复触发:用
.one()替代.on(),确保每个折叠区域的滚动事件只会被触发一次,防止多次点击同一标签时出现重复滚动的问题。
完整示例(HTML+JS)
<!-- 手风琴标签 --> <div class="col-lg-3 col-md-6 col-sm-12 toggling-tabs"> <div class="port-item p-4 bg-primary" data-toggle="collapse" data-target="#home"> <i class="fa fa-home d-block pb-2"></i> Home </div> </div> <div class="col-lg-3 col-md-6 col-sm-12 toggling-tabs"> <div class="port-item p-4 bg-success" data-toggle="collapse" data-target="#resume"> <i class="fa fa-file-text d-block pb-2"></i> Resume </div> </div> <!-- 折叠区域 --> <section class="collapse show sections" id="home"> <div class="card card-body bg-primary text-white py-5 banner"> <h2>Welcome to my portfolio</h2> </div> </section> <section class="collapse sections" id="resume"> <div class="card card-body bg-success text-white py-5"> <h2>My Resume</h2> </div> </section> <!-- 引入依赖 --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <!-- 自定义滚动逻辑 --> <script> $('.toggling-tabs').on('click', function () { const targetCollapseId = $(this).find('[data-toggle="collapse"]').data('target'); const targetSection = $(targetCollapseId); targetSection.one('shown.bs.collapse', function() { $('html, body').animate({ scrollTop: targetSection.offset().top }, 'slow'); }); }); </script>
这个方案可以完美适配所有手风琴标签,点击任意标签都会滚动到对应的折叠区域,且滚动时机和Bootstrap的折叠动画同步,体验更自然。
内容的提问来源于stack exchange,提问作者Tes3awy
相关产品推荐
相关产品推荐

