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

如何实现粘性区块(Sticky Section)随滚动切换颜色?

实现粘性区块随滚动切换颜色的方案

要实现目标网站那样的粘性区块颜色切换,核心是监听页面滚动,检测当前视口对应的产品区域,动态修改粘性区块样式。下面是基于你现有代码的调整方案:

1. 调整HTML结构:划分产品区域

先明确不同颜色对应的产品区块,给每个区块添加标识类名:

<header>header</header>
<main>
  <!-- 独立的粘性区块,确保能全局定位 -->
  <div class="sticky">STICKY</div>
  
  <!-- 产品区域1:对应绿色 -->
  <section class="product-section section-green">产品区域1</section>
  <!-- 产品区域2:对应黄色 -->
  <section class="product-section section-yellow">产品区域2</section>
  <!-- 产品区域3:对应紫色 -->
  <section class="product-section section-purple">产品区域3</section>
</main>
<footer>footer</footer>

2. 调整CSS:完善粘性定位与区块样式

将.sticky设置为固定定位,确保它始终停留在顶部;给每个产品区域设置不同背景色和足够高度:

header {
  height: 100vh;
  background-color: blue;
}

/* 粘性区块核心样式 */
.sticky {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  padding: 1rem;
  text-align: center;
  color: white;
  /* 默认初始底色 */
  background-color: #333;
  z-index: 100;
}

/* 产品区域通用样式 */
.product-section {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 2rem;
}

/* 各区域专属背景色 */
.section-green {
  background-color: #2ecc71;
}
.section-yellow {
  background-color: #f1c40f;
}
.section-purple {
  background-color: #9b59b6;
}

footer {
  height: 100vh;
  background-color: blue;
}

3. JavaScript:监听滚动并切换颜色

通过scroll事件判断当前视口对应的产品区域,修改粘性区块的背景色:

const stickyBlock = document.querySelector('.sticky');
const sections = document.querySelectorAll('.product-section');

window.addEventListener('scroll', () => {
  // 用requestAnimationFrame优化性能,减少频繁重绘
  requestAnimationFrame(() => {
    sections.forEach(section => {
      const sectionTop = section.offsetTop;
      const sectionHeight = section.offsetHeight;
      // 滚动距离加上粘性区块高度,避免区块遮挡判断
      const scrollPos = window.scrollY + stickyBlock.offsetHeight;

      // 判断当前滚动位置是否落在该区块范围内
      if (scrollPos >= sectionTop && scrollPos < sectionTop + sectionHeight) {
        // 获取区块的实际背景色
        const targetColor = getComputedStyle(section).backgroundColor;
        // 给粘性区块设置对应颜色
        stickyBlock.style.backgroundColor = targetColor;
      }
    });
  });
});

关键逻辑说明

  • 位置判断:通过offsetTop获取区块顶部距离页面顶部的坐标,结合滚动距离scrollY,精准匹配当前视口对应的产品区域。
  • 样式复用:用getComputedStyle读取区块的背景色,避免硬编码颜色值,后续修改区块颜色时无需同步调整JS。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 04:05:15