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

如何实现滚动到指定位置时背景图片渐变切换而非上滑移出的效果

滚动触发背景渐变切换实现方案

实现核心逻辑

  • 背景层单独做fixed固定定位,层级放在最底层,内部叠加多张背景图,每张对应一个切换节点
  • 内容层z-index高于背景层,正常流式布局滚动
  • 监听页面滚动事件,计算当前滚动位置匹配预设的触发阈值,修改对应背景图的透明度实现渐变切换

完整代码示例

HTML

<!-- 背景容器 -->
<div class="bg-container">
  <div class="bg-item" style="background-image: url('替换为第一张背景图地址');"></div>
  <div class="bg-item" style="background-image: url('替换为第二张背景图地址');"></div>
  <div class="bg-item" style="background-image: url('替换为第三张背景图地址');"></div>
</div>
<!-- 内容层 -->
<div class="content">
  <section class="section">第一部分内容</section>
  <section class="section">第二部分内容</section>
  <section class="section">第三部分内容</section>
</div>

CSS

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.bg-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: -1;
}
.bg-item {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  opacity: 0;
  transition: opacity 0.8s ease; /* 数值可自定义渐变过渡时长 */
}
/* 默认显示第一张背景 */
.bg-item:first-child {
  opacity: 1;
}
.content {
  z-index: 1;
}
.section {
  height: 100vh; /* 每个内容块占一屏,切换点为每个块的顶部位置,可自定义 */
  padding: 40px;
  font-size: 32px;
  color: #fff;
}

JavaScript

const bgItems = document.querySelectorAll('.bg-item')
const sections = document.querySelectorAll('.section')
// 预设触发位置,这里取每个内容块距离顶部的偏移量,可自定义为固定像素值数组
const triggerPoints = Array.from(sections).map(section => section.offsetTop)

window.addEventListener('scroll', () => {
  const scrollTop = window.pageYOffset
  // 匹配当前滚动位置对应的背景索引
  let activeIndex = triggerPoints.findIndex((point, index) => {
    return scrollTop >= point && (index === triggerPoints.length - 1 || scrollTop < triggerPoints[index + 1])
  })
  // 未匹配到触发点默认显示第一张背景
  activeIndex = activeIndex === -1 ? 0 : activeIndex
  // 调整背景透明度实现渐变切换
  bgItems.forEach((item, index) => {
    item.style.opacity = index === activeIndex ? '1' : '0'
  })
})

自定义调整说明

  • 若不需要每屏切换,可直接修改triggerPoints数组的值为你需要的滚动触发像素值
  • 渐变速度可修改.bg-item的transition属性的时长参数
  • 如果需要切换时增加背景模糊、灰度等效果,可在transition中新增对应属性的过渡配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:24:05