Bootstrap移动端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
相关产品推荐
相关产品推荐

