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

Bootstrap移动端Navbar折叠时页面偏移,如何实现折叠并回滚指定像素?

解决Bootstrap Sticky Navbar折叠后页面下移的问题

问题核心是Bootstrap的collapse组件执行collapse('hide')时带有过渡动画,动画过程中页面高度变化会触发浏览器自动调整滚动位置,导致你手动设置的scrollTop被覆盖。

解决方案:监听折叠完成事件再调整滚动位置

利用Bootstrap collapse组件的hidden.bs.collapse事件(动画完全结束后触发),在此时调整滚动位置就能避免被覆盖。同时处理锚链接的跳转逻辑,避免冲突:

$('.nav-link, .navbar-brand').on('click', function(e) {
    e.preventDefault();
    const targetHref = $(this).attr('href');
    const $collapse = $('#navbarSupportedContent');

    if ($collapse.hasClass('show')) {
        // 记录当前滚动位置
        const currentScroll = $(window).scrollTop();
        // 触发菜单折叠
        $collapse.collapse('hide');
        // 折叠完成后执行滚动调整和跳转
        $collapse.one('hidden.bs.collapse', function() {
            // 回滚指定高度
            $(window).scrollTop(currentScroll - 296);
            // 处理锚链接或外部链接跳转
            if (targetHref.startsWith('#')) {
                const scrollTarget = targetHref === '#top' ? 0 : $(targetHref).offset().top;
                $('html, body').animate({ scrollTop: scrollTarget }, 300);
            } else {
                window.location.href = targetHref;
            }
        });
    } else {
        // 菜单已折叠时直接处理跳转
        if (targetHref.startsWith('#')) {
            const scrollTarget = targetHref === '#top' ? 0 : $(targetHref).offset().top;
            $('html, body').animate({ scrollTop: scrollTarget }, 300);
        } else {
            window.location.href = targetHref;
        }
    }
});

关键说明

  • 使用one('hidden.bs.collapse')确保事件只触发一次,避免重复绑定。
  • 先阻止默认锚点跳转(e.preventDefault()),防止浏览器自动滚动和自定义逻辑冲突。
  • 动态判断菜单是否处于展开状态(hasClass('show')),只在需要折叠时执行滚动调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 17:55:01