GSAP ScrollTrigger动画期间元素未固定问题求助
问题描述
我是GSAP新手,可能操作方式有误。我制作了一个示例,GSAP设置如下:
gsap.to(".before", { scrollTrigger: { trigger: ".flex", start: "top top", end: () => "+=" + document.querySelector(".before").offsetWidth, scrub: "true", pin: "true", toggleAction: "play none none reverse" }, x: '-100%', duration: 2 }); gsap.to(".after", { scrollTrigger: { trigger: ".flex", start: "top top", end: () => "+=" + document.querySelector(".after").offsetWidth, scrub: "true", pin: "true", toggleAction: "play none none reverse" }, x: '100%', duration: 2 });
我希望动画期间固定gsap-container容器,直到背景完全显示后再继续向下滚动。原本以为设置pin: true可以实现,但现在仍能滚动到下方的红框区域,请问哪里操作错了?
解决方案
- 避免重复设置pin:你给两个不同的ScrollTrigger都加了
pin: true,这会导致GSAP的滚动计算冲突——同一个.flex元素被两个pin操作同时控制,无法正确锁定容器。只需要在其中一个ScrollTrigger上保留pin: true即可,比如保留第一个动画的pin设置,移除第二个的。 - 统一end值:两个动画的
end应该保持一致,否则滚动范围不匹配,也会导致pin失效或滚动异常。可以直接用gsap-container的宽度来计算end值,确保两个动画的滚动触发范围完全同步。 - 优化后的代码示例:
// 提前获取容器宽度,统一用在两个动画的end参数中 const containerWidth = document.querySelector(".gsap-container").offsetWidth; gsap.to(".before", { scrollTrigger: { trigger: ".flex", start: "top top", end: `+=${containerWidth}`, scrub: true, pin: true, // 仅在一个ScrollTrigger中设置pin toggleAction: "play none none reverse" }, x: '-100%', duration: 2 }); gsap.to(".after", { scrollTrigger: { trigger: ".flex", start: "top top", end: `+=${containerWidth}`, scrub: true, toggleAction: "play none none reverse" }, x: '100%', duration: 2 });
修改后,gsap-container会在动画执行期间被固定,直到左右两个滑动动画完全结束,才能继续向下滚动到下方的红框区域。
内容的提问来源于stack exchange,提问作者Miu_19
相关产品推荐
相关产品推荐

