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

为什么GSAP动画循环无限运行?ScrollTrigger无法停止循环

解决滚动触发/停止无限图片切换动画的问题

你的代码存在几个关键问题,导致动画无法按预期在进入区块时启动、离开时停止,且重复切换逻辑失效,以下是修正方案:

问题分析

  • 动画 timeline 初始化时未设置默认暂停,页面加载后会直接开始循环,完全无视滚动位置
  • onComplete 回调里的图片切换逻辑仅在首次遍历图片时生效,timeline 重复时不会更新图片索引,导致后续重复无法切换新图片
  • ScrollTrigger 只处理了onEnter(向下进入区块)和onLeaveBack(向上滚出区块),未覆盖onLeave(向下滚出区块)的场景,导致向下滚动离开后动画仍在运行

修正后的代码

const images = ['/img/Landing/section/chat.png', '/img/Landing/section/chat1.png', '/img/Landing/section/chat2.png'];
const myImage = document.getElementById('section-img');
let currentIndex = 0;

// 封装单步图片切换的动画逻辑
function switchImage() {
  gsap.to(myImage, {
    duration: 1,
    opacity: 0,
    onComplete: () => {
      // 更新图片索引,实现循环切换
      currentIndex = (currentIndex + 1) % images.length;
      myImage.src = images[currentIndex];
      // 切换图片后淡入显示
      gsap.to(myImage, { duration: 1, opacity: 1 });
    }
  });
}

// 创建循环动画timeline,默认暂停
const imageSwitchTimeline = gsap.timeline({
  repeat: -1,
  repeatDelay: 0.5,
  paused: true // 初始状态暂停,等待滚动触发
});

// 将单步切换逻辑加入timeline
imageSwitchTimeline.add(switchImage);

ScrollTrigger.create({
  trigger: '#section',
  start: 'top center',
  end: 'bottom center',
  // 向下进入/向上回滚进入时启动动画
  onEnter: () => imageSwitchTimeline.play(),
  onEnterBack: () => imageSwitchTimeline.play(),
  // 向下离开/向上回滚离开时暂停动画
  onLeave: () => imageSwitchTimeline.pause(),
  onLeaveBack: () => imageSwitchTimeline.pause()
});

关键改进点

  • 初始设置paused: true,确保页面加载后动画不会自动运行,完全由滚动事件控制
  • 用独立函数处理图片切换逻辑,每次触发时更新索引,保证循环时能遍历所有图片
  • 完善ScrollTrigger的所有触发场景,覆盖上下滚动的进入/离开动作
  • 调整动画流程:先淡出当前图片,切换src后再淡入,过渡更自然流畅

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 03:00:08