使用 useEffect 不工作在 Scroll 上移动图像

Moving an image on Scroll using useEffect not Working

目前我正在尝试使用 useEffect 来操纵我的 DOM 元素来创建视差效果。我想要实现的是:

其中图像垂直固定在屏幕中间,可以水平移动,第一个文本垂直向上移动,第二个文本从图像下方从左到右水平移动。但是现在我的图片并没有左右移动,第二个 window 中的文字也没有按照我想要的方式移动。

代码沙箱:https://codesandbox.io/s/fixedscroll-n952b?file=/src/App.js

代码:

useEffect(function onFirstMount() {
    const changeBackground = () => {
      let value = window.scrollY;
      let img = document.getElementById("moveLeft");
      let text = document.getElementById("moveUp");
      let text2 = document.getElementById("text2");

      img.style.left = value * 0.5 + "px";
      text.style.marginTop = "-" + value * 0.5 + "px";
      text2.style.left = value * 1 + "px";
    };
    window.addEventListener("scroll", changeBackground);
    return () => window.removeEventListener("scroll", changeBackground);
  }, []);

  return (
    <>
      <div className="App">
        <div class="inflow">
          <div class="positioner">
            <div class="fixed">
              <div
                id="moveUp"
                style={{
                  position: "absolute",
                  color: "#fff",
                  fontSize: "40px"
                }}
              >
                VANATAU
              </div>
              <div id="moveLeft">
                <img
                  alt="passport"
                  src="https://cdn.britannica.com/87/122087-050-1C269E8D/Cover-passport.jpg"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className="App2">
        <div className="half">
          <div className="text2" id="text2">
            MINIMUM INVESTMENT
          </div>
        </div>
      </div>
      <div className="App2"></div>

您正在 position: static 元素 (div) 上设置 property。 您应该将 position: absolute 添加到 #moveLeft 或使用 translateX:

img.style.transform = `translateX(${value * 0.5}px)`