使用ScrollTrigger如何默认显示初始内容并保留最终内容
解决ScrollTrigger初始内容空白与滚动结束保留最后内容的问题
问题描述
用ScrollTrigger实现滚动动画时,遇到两个问题:
- 初始状态下亮绿色内容区域为空白,希望在区块固定前就显示首个内容
- 区块滚动结束后,希望保留最后一个内容不消失
解决方案及代码修改
针对问题,调整代码如下:
// 初始隐藏所有内容,然后单独显示第一个内容 gsap.set('.content',{ autoAlpha: 0 }) gsap.set('.content-0',{ autoAlpha: 1 }) var headlines = gsap.utils.toArray(".text"); var totalDuration = 8000; var singleDuration = totalDuration / headlines.length; const lineTimeline = gsap.timeline(); // 主滚动固定动画 ScrollTrigger.create({ trigger: ".pin-up", start: "top top", end: "+=" + totalDuration, pin: true, scrub: true, animation: lineTimeline, }); headlines.forEach((elem, i) => { const smallTimeline = gsap.timeline(); const content = document.querySelector('.content-wrap'); const relevantContent = content.querySelector('div.content-' + i); // 针对最后一个元素调整toggleActions,避免反向隐藏 let toggleActions = "play reverse play reverse"; if (i === headlines.length - 1) { toggleActions = "play none none none"; } ScrollTrigger.create({ trigger: ".pin-up", start: `top top+=${singleDuration * i}`, end: `+=${singleDuration}`, animation: smallTimeline, toggleActions: toggleActions, containerAnimation: lineTimeline // 关联主滚动动画,确保同步 }); smallTimeline .to(elem,{ duration: 0.25, color: "orange"}, 0) .to(elem.firstChild,{ duration: 0.25, backgroundColor: "orange", width: "50px"}, 0) .set(relevantContent,{ autoAlpha: 1 }, 0) // 非最后一个元素,在时间线结束时隐藏内容 .add(() => { if (i !== headlines.length - 1) { gsap.set(relevantContent, { autoAlpha: 0 }); } }, smallTimeline.duration()); });
关键改动说明
- 初始显示首个内容:在全局隐藏
.content后,单独设置.content-0的autoAlpha:1,直接解决初始空白问题。 - 同步主滚动进度:将小ScrollTrigger的trigger改为与主动画一致的
.pin-up,并通过containerAnimation关联主时间线,避免基于body滚动的位置计算误差。 - 保留最后内容:对最后一个元素的
toggleActions设置为"play none none none",取消反向执行逻辑,确保滚动结束后内容保持显示。 - 自动切换内容:为非最后一个元素添加时间线结束回调,自动隐藏当前内容,配合
toggleActions的reverse动作,实现滚动到下一个内容时自动切换。
内容的提问来源于stack exchange,提问作者wertyu
相关产品推荐
相关产品推荐

