vue 前端pc自适应方案

1,070 阅读1分钟

总结:通过postcss-pxtorem 插件,将 px 转换成 rem,适配各种尺寸的pc屏幕。

步骤如下:

1.安装 postcss-pxtorem 插件

安装 postcss-pxtorem 插件:`$ npm install postcss postcss-pxtorem --save-dev`

2.新建 postcss.config.js 文件:

module.exports = {
    plugins: {
      "postcss-pxtorem": {
        rootValue: 10, // 1rem=10px
        propList: ["*"],
        unitPrecision: 2,
        exclude: /(node_module)/,
      },
    },
};

3.新建并引入 rem.js 文件

// 设置 rem 函数
function setRem() {
  const scale = document.documentElement.clientWidth / 1920;
  document.documentElement.style.fontSize = 10 * scale + "px";
}

export const initRem = () => {
  // 调用一次,初始化rem
  setRem();
  const i = "orientationchange" in window ? "orientationchange" : "resize";

  // 改变窗口大小时重新设置 rem,用节流防止改变窗口大小时卡死
  let timer = undefined;
  window.addEventListener(i, function () {
    if (timer) {
      clearTimeout(timer);
    }
    timer = window.setTimeout(() => {
      setRem();

      clearTimeout(timer);
    }, 200);
  });
};

initRem();

4.运行项目,查看适配效果。