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

非顶部时为粘性Bootstrap导航栏添加阴影的实现问题

解决Bootstrap滚动导航栏顶部状态阴影残留问题

你的思路完全可行,通过新增.on-top类可以精准控制导航栏在页面顶部时的无阴影状态,同时让滚动显示的导航栏保持阴影效果。只需修改JavaScript逻辑和CSS样式即可实现:

1. 调整JavaScript逻辑

在滚动事件监听中增加页面顶部判断,当滚动距离为0时,移除.scrolled-up和.scrolled-down类,添加.on-top类;否则按原有逻辑处理滚动方向对应的类:

document.addEventListener("DOMContentLoaded", function(){
  const el_autohide = document.querySelector('.autohide');
  const navbar_height = document.querySelector('.navbar').offsetHeight;
  document.body.style.paddingTop = navbar_height + 'px';

  if(el_autohide){
    let last_scroll_top = 0;
    window.addEventListener('scroll', function() {
      const scroll_top = window.scrollY;
      
      // 回到页面顶部时,切换到on-top类
      if(scroll_top === 0) {
        el_autohide.classList.remove('scrolled-up', 'scrolled-down');
        el_autohide.classList.add('on-top');
      } 
      // 向上滚动时显示导航栏
      else if(scroll_top < last_scroll_top) {
        el_autohide.classList.remove('scrolled-down', 'on-top');
        el_autohide.classList.add('scrolled-up');
      } 
      // 向下滚动时隐藏导航栏
      else {
        el_autohide.classList.remove('scrolled-up', 'on-top');
        el_autohide.classList.add('scrolled-down');
      }
      
      last_scroll_top = scroll_top;
    });
  }
});

2. 更新CSS样式

给.scrolled-up和.scrolled-down添加阴影效果,同时给.on-top设置无阴影,确保顶部状态的样式优先级:

/* 顶部状态:无阴影 */
.on-top {
  transform: translateY(0);
  transition: all 0.3s ease-in-out;
  background: #fff !important; /* 根据需求调整背景色 */
  box-shadow: none !important;
}

/* 向上滚动显示:带阴影 */
.scrolled-up {
  transform: translateY(0);
  transition: all 0.3s ease-in-out;
  background: green !important;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important; /* 自定义阴影样式 */
}

/* 向下滚动隐藏:带阴影(隐藏状态下也可保留,或根据需求移除) */
.scrolled-down {
  transform: translateY(-100%);
  transition: all 0.3s ease-in-out;
  background: red !important;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;
}

.autohide {
  position: fixed !important;
  top: 0;
  right: 0;
  left: 0;
  width: 100%;
  z-index: 1030;
}

关键说明

  • 当页面回到顶部(scrollY === 0)时,强制切换到.on-top类,确保导航栏无阴影;
  • 滚动过程中,每次切换类时都要移除其他状态的类,避免样式冲突;
  • 阴影样式可根据设计需求调整box-shadow的参数,比如模糊度、颜色等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:25:26