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

如何用单个类/动态属性实现Bootstrap 4手风琴点击按钮后锚定到对应标题并加动画?

优化后的实现方案

直接用你已有的.collapse-anchor类统一绑定事件,不用再为每个ID写重复代码,同时保留原有的跨页面锚定功能:

修改后的JavaScript代码

$(document).ready(function(){
  function myFunc() {
    // 处理锚点触发的折叠展开
    location.hash && $(location.hash + '.collapse-anchor').collapse('show');
    history.pushState("", document.title, window.location.pathname);
    
    $('.collapse-anchor').on('show.bs.collapse', function (e) {
      // 获取触发折叠操作的元素(保留原逻辑)
      clicked = $(document).find("[href='#" + $(e.target).attr('id') + "']")
    });

    // 给所有折叠面板统一绑定展开完成事件
    $('.collapse-anchor').on('shown.bs.collapse', function () {
      const $currentPanel = $(this);
      setTimeout(function() {
        $('html, body').animate({
          scrollTop: $currentPanel.prev('.card-header').offset().top
        }, 500);
      }, 500);
    })
  };
  myFunc();
});

核心优化说明

  • 删掉了针对#collapseTab2-1、#collapseTab2-2等单个ID的重复事件绑定,改用.collapse-anchor类一次性覆盖所有折叠面板
  • 事件回调里用$(this)指代当前刚展开的折叠面板,动态获取它对应的.card-header,实现通用化逻辑
  • 原有的锚点处理逻辑完全保留,依然支持跨页面锚定到指定区块

优势

后续新增折叠面板时,只要给它加上.collapse-anchor类,就能自动获得展开后滚动到标题的功能,不用再修改JS代码,扩展性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 03:12:33