移动端适配

2020-11-05  本文已影响0人  sweetBoy_9126

1.使用postcss-pxtorem插件将px转成动态rem

因为rem是根据根元素html的值为基准来动态转换px的,也就是说html是多少像素那么1rem就是多少像素,所以我们必须先根据屏幕的宽度来设置我们的html元素的px值。

新建rem.js文件,在main.js中引用

// 设计稿以750px为宽度,而我把页面宽度设计为10rem的情况下

const baseSize = 75; // 这个是设计稿中1rem的大小。
function setRem() {
    // 实际设备页面宽度和设计稿的比值
    const scale = document.documentElement.clientWidth / 750;
    // 计算实际的rem值并赋予给html的font-size
    document.documentElement.style.fontSize = (baseSize * scale) + 'px';
}
setRem();
window.addEventListener('resize', () => {
    setRem();
});

1.1. 安装postcss-pxtorem
postcss-pxtorem是PostCSS的插件,用于将px单位生成rem单位。

yarn add postcss-pxtorem

1.2 配置

可以通过3个地方来添加配置,配置文件皆位于vue 项目根目录中,若文件不存在可以自行建立。

其中最重要的是这个:

还有一些其他的配置:

完整的可以看官方文档

配置示例
vue.config.js

module.exports = {
    //...其他配置
    css: {
      loaderOptions: {
        postcss: {
          plugins: [
            require('postcss-pxtorem')({
              rootValue: 192,
              minPixelValue: 2,
              propList: ['*'],
            })
          ]
        }
      }
    },
  }

postcssrx.js

module.exports = {
    plugins: {
        'postcss-pxtorem': {
            rootValue: 16,
            minPixelValue: 2,
            propList: ['*'],
        }
    }
}

postcss.config.js

module.exports = {
  plugins: {
    'postcss-pxtorem': {
      rootValue: 192,
      minPixelValue: 2,
      propList: ['*'],
    }
  }
}
上一篇 下一篇

猜你喜欢

热点阅读