【问题标题】:Getting width of screen using window.innerwidth not working使用 window.innerwidth 获取屏幕宽度不起作用
【发布时间】:2026-02-23 10:10:01
【问题描述】:

目前我正在尝试使用 useEffect 来制作视差效果来操作我的 DOM 元素,但这不是响应式的。所以目前要解决这个问题,我正在尝试获取屏幕宽度并添加条件,以便每当屏幕具有特定大小时,它应该以特定方式更改 DOM 元素。为了获得我正在使用的屏幕宽度 const width = window.innerWidth; 但这给了我一个

ReferenceError: 未定义窗口

我在我的代码框上试过了,但它并没有用完全相同的代码给我这个错误。所以我对此有两个问题。一是我如何摆脱这个错误,二是有没有更好的方法可以在不指定每个屏幕的宽度并相应地更改 DOM 的情况下使其响应?

代码沙盒:https://codesandbox.io/s/laughing-pascal-vc45v?file=/src/App.js

代码:

export default function App() {
  const width = window.innerWidth;
  console.log(width);
  if(width>1000){
  useEffect(function onFirstMount() {
    const changeBackground = () => {
      let value = window.scrollY;

      let img = document.getElementById("moveLeft");
      let text = document.getElementById("moveUp");

      let imgWidth = 280;

      text.style.marginTop = "-" + value * 0.5 + "px";
      text2.style.transform = `translateX(${value * 1.3}px)`;

      if (value > 600) {
        img.style.transform = `translateX(${value * 0.8 - 480 - imgWidth}px)`;
      } else {
        img.style.transform = `translateX(-${value * 0.5}px)`;
      }

      if (value > 1400) {
        img.style.transform = `translateX(${
          -1 * (value * 0.8 - 1120) + 80 + imgWidth
        }px)`;
      }

      if (value > 1700) {
        setNumber(true);
      } else {
        setNumber(false);
      }
    };
    window.addEventListener("scroll", changeBackground);
    return () => window.removeEventListener("scroll", changeBackground);
  }, []);
}

【问题讨论】:

    标签: javascript css reactjs css-animations


    【解决方案1】:

    您的页面是服务器端渲染的,因此来自服务器的window 未定义。

    您可以使用下面的示例摆脱它

    const width = window?.innerWidth || yourDefaultWidth
    

    但为了更好地从 SSR 获取正确的窗口尺寸,请查看this

    【讨论】:

      【解决方案2】:

      要根据浏览器动态更改样式,最好在 CSS 文件中使用媒体查询。

      @media only screen and (max-width: 200px) {
        body {
          margin-top: 20px;
        }
      }
      
      @media only screen and (max-width: 480px) {
        body {
          margin-top: 40px;
        }
      }
      

      【讨论】: