我正在使用 GSAP 和 Locomotive 在 React 项目中制作一个简单的动画。但我遇到一个问题,开始和结束标记不固定并随着滚动移动。我认为我已经很好地完成了 GSAP 和 Locomotive 设置。
奇怪的是,当我在codesandbox的常规模式下滚动时,标记是固定的并且工作良好。但是,当我单击codesandbox 中的“切换响应式预览”按钮并刷新,然后尝试滚动时,标记不会保持固定并随着滚动而移动。在codesandbox之外的真实本地环境中,标记也不会保持固定,并表现出相同的行为,随着滚动而移动。
我可以知道是什么问题吗??
代码沙盒
https://codesandbox.io/s/locomotive-gsap-xsq7lf?file=/src/App.js
Page.jsx
import React, { useEffect, useRef } from "react";
import LocomotiveScroll from "locomotive-scroll";
import { gsap, ScrollTrigger } from "gsap/all";
import "../locomotiveStyle/locomotive-scroll.css";
import { Wrap } from "./PageStyle";
import One from "../components/one/One";
import Two from "../components/two/Two";
const Page = () => {
const wrapRef = useRef(null);
const containerRef = useRef(null);
const oneRef = useRef(null);
const twoRef = useRef(null);
gsap.registerPlugin(ScrollTrigger);
//locomotive setting
useEffect(() => {
const locoScroll = new LocomotiveScroll({
el: document.querySelector(".container"),
smooth: true
});
locoScroll.on("scroll", ScrollTrigger.update);
ScrollTrigger.scrollerProxy(".container", {
scrollTop(value) {
return arguments.length
? locoScroll.scrollTo(value, 0, 0)
: locoScroll.scroll.instance.scroll.y;
},
getBoundingClientRect() {
return {
top: 0,
left: 0,
width: window.innerWidth,
height: window.innerHeight
};
},
pinType: document.querySelector(".container").style.transform
? "transform"
: "fixed"
});
ScrollTrigger.addEventListener("refresh", () => locoScroll.update());
ScrollTrigger.refresh();
}, []);
//GSAP
useEffect(() => {
let tl = gsap.timeline({
scrollTrigger: {
trigger: oneRef.current,
start: "75% center",
end: "105% center",
scrub: true,
markers: true
}
});
tl.to(twoRef.current, {
x: 300,
duration: 5
});
}, []);
return (
<Wrap ref={wrapRef}>
<div ref={containerRef} className="container">
<One ref={oneRef} />
<Two ref={twoRef} />
</div>
</Wrap>
);
};
export default Page;
One.jsx
Two.jsx 与 One.jsx 相同
import React, { forwardRef } from "react";
import { Wrap } from "./OneStyle";
const One = React.forwardRef((props, ref) => {
return (
<Wrap ref={ref}>
<span>1</span>
</Wrap>
);
});
export default One;
也许您需要更新滚动触发器 ScrollTrigger.update
与莱尼斯: lenis.on('滚动', () => ScrollTrigger.update());