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

Bootstrap 5 窗口resize时导航栏collapse折叠无过渡动画如何解决

解决方法

直接手动移除show类不会触发Bootstrap内置的过渡动画,你需要调用Bootstrap 5 Collapse组件的官方API来执行折叠操作,同时添加防抖逻辑优化resize事件的性能,优化后代码如下:

JS代码(兼容现有jQuery写法)

$(document).ready(function() {
  // 防抖函数,避免窗口调整时频繁触发逻辑
  function debounce(func, delay = 150) {
    let timer;
    return function(...args) {
      clearTimeout(timer);
      timer = setTimeout(() => func.apply(this, args), delay);
    }
  }

  const collapseDom = document.getElementById('bs-navbar-collapse');
  // 初始化Bootstrap Collapse实例
  const bsCollapse = new bootstrap.Collapse(collapseDom, {
    toggle: false // 初始化时不改变菜单现有状态
  });

  $(window).resize(debounce(function() {
    // 仅当窗口宽度超过md断点(768px)且菜单处于展开状态时执行折叠
    if (window.innerWidth >= 768 && collapseDom.classList.contains('show')) {
      bsCollapse.hide(); // 调用官方hide方法,自动触发平滑折叠动画
      // 同步重置汉堡按钮状态
      $('.navbar-toggler').addClass('collapsed').attr('aria-expanded', 'false');
    }
  }));
});

注意事项

  • 如果你后续修改了导航栏的响应式断点,比如把navbar-expand-md改为navbar-expand-lg,需要把代码中的宽度判断值从768对应改为992
  • 150ms的防抖延迟可根据需求调整,不建议设置过短,避免不必要的性能消耗

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:39:03