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

如何根据固定NavBar当前覆盖的div动态调整其背景颜色

实现方案

方案1:纯CSS实现(现代浏览器支持,性能最优)

利用CSS滚动驱动动画匹配每个区块的颜色,无需写JS逻辑,适合区块高度固定的场景:

/* 给每个内容区块设置对应高度 */
.section {
  height: 100vh;
  width: 100%;
}
/* NavBar基础样式 */
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 60px;
  z-index: 999;
  /* 绑定滚动驱动动画 */
  animation: adjust-nav-bg linear both;
  animation-timeline: scroll(root);
}
/* 按实际区块数量、滚动占比定义对应阶段的NavBar背景色 */
@keyframes adjust-nav-bg {
  /* 第一个区块占0-25%滚动高度区间 */
  0%, 25% {
    background-color: #ffffff;
  }
  /* 第二个区块占25%-50%滚动高度区间 */
  25%, 50% {
    background-color: #f0f4f8;
  }
  /* 后续区块按实际高度占比依次补充即可 */
  50%, 75% {
    background-color: #1a202c;
  }
  75%, 100% {
    background-color: #e6fffa;
  }
}

方案2:JS实现(全浏览器兼容,适配动态高度区块)

监听滚动事件实时判断NavBar当前覆盖的区块,同步背景色即可,适合区块高度不固定、有动态内容的场景:

// 提前获取所有内容区块和NavBar元素
const sections = document.querySelectorAll('.section')
const navBar = document.querySelector('.navbar')
// 获取NavBar自身高度作为判定基准
const navHeight = navBar.offsetHeight

window.addEventListener('scroll', () => {
  // 取NavBar底部的位置作为覆盖判定点
  const navBottomY = window.scrollY + navHeight
  // 遍历所有区块匹配当前覆盖的区块
  for (const section of sections) {
    const sectionTop = section.offsetTop
    const sectionBottom = sectionTop + section.offsetHeight
    if (navBottomY >= sectionTop && navBottomY < sectionBottom) {
      // 同步当前区块的背景色到NavBar
      navBar.style.backgroundColor = window.getComputedStyle(section).backgroundColor
      break
    }
  }
})

如果页面有懒加载内容导致区块高度动态变化,只需要在内容加载完成后手动触发一次scroll事件即可同步逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:09:00