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

如何使用原生JavaScript实现单次滚动事件切换多张背景图片序列

单次滚动切换多张背景图片的实现方案

核心逻辑

  • 禁用浏览器默认滚动行为,避免干扰自定义切换逻辑
  • 监听滚轮事件,判断滚动方向(向上/向下)
  • 用定时器批量切换图片,同时加锁防止快速滚动触发重复动画

完整代码实现

HTML结构

<div class="bg-container"></div>

样式设置

.bg-container {
  position: fixed;
  width: 100vw;
  height: 100vh;
  background-size: cover;
  background-position: center;
  /* 单张图片切换的过渡动画,和JS里的切换间隔对应 */
  transition: background-image 0.3s ease;
}

JavaScript逻辑

const bgContainer = document.querySelector('.bg-container');
// 替换成你的背景图片序列
const bgList = [
  './images/bg-1.jpg',
  './images/bg-2.jpg',
  './images/bg-3.jpg',
  './images/bg-4.jpg',
  './images/bg-5.jpg'
];
let currentImgIndex = 0;
const switchNum = 3; // 单次滚动要切换的图片数量
let isSwitching = false; // 防止滚动触发叠加动画

// 监听滚轮事件
bgContainer.addEventListener('wheel', (e) => {
  e.preventDefault(); // 阻止浏览器原生滚动
  if (isSwitching) return; // 正在切换时不响应新的滚动

  // 判断滚动方向:向下滚为正,向上滚为负
  const scrollDir = e.deltaY > 0 ? 1 : -1;
  isSwitching = true;

  let switchedCount = 0;
  // 设置定时器批量切换图片
  const switchTimer = setInterval(() => {
    switchedCount++;
    // 更新图片索引,处理循环边界
    currentImgIndex = (currentImgIndex + scrollDir + bgList.length) % bgList.length;
    bgContainer.style.backgroundImage = `url(${bgList[currentImgIndex]})`;

    // 达到设定切换数量后停止
    if (switchedCount === switchNum) {
      clearInterval(switchTimer);
      // 等待最后一张图的过渡动画完成后解锁
      setTimeout(() => {
        isSwitching = false;
      }, 300);
    }
  }, 300); // 每张图片的切换间隔,和CSS过渡时间保持一致
});

关键细节提示

  • 切换锁isSwitching:必须加这个判断,不然用户快速滚动会导致动画混乱
  • 过渡时间匹配:CSS的transition时长和JS定时器的间隔要一致,保证切换流畅
  • 索引循环处理:用取余运算让图片序列可以循环切换,不会出现索引越界的问题
  • 全屏覆盖:容器要设置fixed定位并占满全屏,确保滚轮事件能被正确监听

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:31:04