GSAP ScrollTrigger在ReactJS中无法正常工作的问题求助
滚动时黑色方块无法逐步旋转的问题修复
你的代码存在几个关键问题导致旋转效果不生效:
- 多个
ScrollTrigger同时控制同一个元素(黑色方块),后创建的动画会直接覆盖之前的,最终只有最后一个旋转(360度)的逻辑生效,无法实现逐步旋转的效果。 - 滚动容器是内部的
div(带有overflow-scroll的那个),但ScrollTrigger默认监听window的滚动事件,而你的页面滚动发生在内部容器中,触发器根本检测不到滚动动作。 duration参数在scrub: true模式下会被忽略,scrub模式的动画时长由滚动距离决定,不需要额外设置。
修正后的代码
import React, { useEffect, useRef } from "react"; import gsap from "gsap"; import { ScrollTrigger } from "gsap/ScrollTrigger"; gsap.registerPlugin(ScrollTrigger); export default function TEST() { const boxRef = useRef(null); const containerRef = useRef(null); // 新增滚动容器的ref useEffect(() => { // 使用时间线串联四个阶段的旋转动画 const timeline = gsap.timeline({ scrollTrigger: { trigger: containerRef.current, scroller: containerRef.current, // 指定监听内部滚动容器 start: "top top", end: "bottom bottom", // 滚动到容器底部时完成整个动画 scrub: true, // 滚动与动画进度绑定 }, }); // 依次添加每个阶段的旋转动作,每个阶段对应一个全屏区块的滚动 timeline .to(boxRef.current, { rotation: 90 }) .to(boxRef.current, { rotation: 180 }) .to(boxRef.current, { rotation: 270 }) .to(boxRef.current, { rotation: 360 }); }, []); return ( <div ref={containerRef} className="h-screen w-screen overflow-scroll overflow-x-hidden scrollbar-thin" > <div ref={boxRef} className="box top-96 left-96 fixed h-14 w-14 bg-black" ></div> <div className="one h-screen w-full bg-white"></div> <div className="two h-screen w-full bg-slate-600"></div> <div className="three h-screen w-full bg-red-600"></div> <div className="four h-screen w-full bg-yellow-600"></div> </div> ); }
关键调整说明
- 使用GSAP时间线:把四个旋转阶段串联成一个连贯的动画,确保滚动过程中方块逐步完成90°→180°→270°→360°的旋转。
- 指定滚动容器:通过
scroller参数告诉ScrollTrigger监听内部容器的滚动事件,这样触发器才能正确响应滚动动作。 - 移除冗余参数:删掉了无效的
duration参数,scrub模式下动画进度由滚动位置直接控制。
内容的提问来源于stack exchange,提问作者SaUrAv kS
相关产品推荐
相关产品推荐

