为什么我的rem配置失败,不能随着窗口的变化让内容自适应?

为什么我的rem配置失败,不能随着窗口的变化让内容自适应?

这是配置rem.js的文件

function remSize() {
  // 获取设备的宽度
  var deviceWidth = document.documentElement.clientWidth || window.innerWidth;
  if (deviceWidth >= 750) {
    deviceWidth = 750;
  }
  if (deviceWidth <= 320) {
    deviceWidth = 320;
  }
  // 这是html的
  document.documentElement.style.fontSize = deviceWidth / 7.5 + "px";
  // 设置字体大小 350/7.5 * 0.3
  document.querySelector("body").style.fontSize = 0.3 + "rem";
}
remSize();
// DOM事件,当浏览器窗口大小变化时,自动会调用这个函数
window.onresize = function () {
  remSize();
};

到index.html去调用
代码在倒数第三行的位置

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <link rel="icon" href="<%= BASE_URL %>favicon.ico" />
    <!-- 引入图标 -->
    <script src="//at.alicdn.com/t/c/font_3652123_ca4x3n3wg19.js"></script>
    <title><%= htmlWebpackPlugin.options.title %></title>
    <style type="text/css">
      .icon {
        width: 1em;
        height: 1em;
        vertical-align: -0.15em;
        fill: currentColor;
        overflow: hidden;
      }
    </style>
  </head>
  <body>
    <noscript>
      <strong
        >We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work
        properly without JavaScript enabled. Please enable it to
        continue.</strong
      >
    </noscript>
    <div id="app"></div>
    <!-- 把写的适配代码引入过来 -->
    <script src="<%= BASE_URL %>js/rem.js"></script>
  </body>
</html>

当我改变窗口大小,但内容大小没自适应

img

img

【以下回答由 GPT 生成】

问题出在remSize()函数中没有正确地计算和设置根元素的字体大小。下面是修正后的代码:

function remSize() {
  // 获取设备的宽度
  var deviceWidth = document.documentElement.clientWidth || window.innerWidth;
  if (deviceWidth >= 750) {
    deviceWidth = 750;
  }
  if (deviceWidth <= 320) {
    deviceWidth = 320;
  }
  // 设置根元素的字体大小为设备宽度的1/7.5倍
  document.documentElement.style.fontSize = deviceWidth / 7.5 + "px";
}

remSize();

// 当浏览器窗口大小变化时,自动调用remSize函数
window.onresize = function () {
  remSize();
};

修改后的代码去掉了设置body字体大小的部分,因为我们的目标是让整个页面的元素根据根元素的字体大小自适应,而不是仅仅改变body的字体大小。

另外,为了确保remSize()函数在页面加载时和窗口大小变化时都会被调用,可以将代码放在<script>标签中,并放在<body>标签的最后,如下所示:

<!DOCTYPE html>
<html>
  <head>
    <title>My Website</title>
    <!-- 其他head相关内容 -->
  </head>
  <body>
    <!-- 页面内容 -->

    <script>
      function remSize() {
        var deviceWidth = document.documentElement.clientWidth || window.innerWidth;
        if (deviceWidth >= 750) {
          deviceWidth = 750;
        }
        if (deviceWidth <= 320) {
          deviceWidth = 320;
        }
        document.documentElement.style.fontSize = deviceWidth / 7.5 + "px";
      }

      remSize();

      window.onresize = function () {
        remSize();
      };
    </script>
  </body>
</html>

通过以上修改,应该可以解决你的问题,让rem配置可以随窗口大小的变化而自适应。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^