美文网首页
移动端适配

移动端适配

作者: sweetBoy_9126 | 来源:发表于2020-11-05 14:04 被阅读0次

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 项目根目录中,若文件不存在可以自行建立。

其中最重要的是这个:

  • rootValue (Number)

    • 根元素的值,即1rem的值
    • 用于设计稿元素尺寸/rootValue
    • 比如 rootValue = 75 时,在css中width: 375px; 最终会换算成width: 5rem;

还有一些其他的配置:

  • propList (Array) 需要做单位转化的属性.

    • 必须精确匹配
    • 用 * 来选择所有属性. Example: ['*']
    • 在句首和句尾使用 * (['position'] 会匹配 background-position-y)
    • 使用 ! 来配置不匹配的属性. Example: ['*', '!letter-spacing']
    • 组合使用. Example: ['', '!font']
  • minPixelValue(Number) 可以被替换的最小像素.

  • unitPrecision(Number) rem单位的小数位数上限.

完整的可以看官方文档

  • 权重
    vue.config.js > .postcssrx.js > postcss.config.js
    其中 postcssrc.js 和 postcss.config.js 可以热更新, vue.config.js 中做的修改要重启devServer

配置示例
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: ['*'],
    }
  }
}

相关文章

网友评论

      本文标题:移动端适配

      本文链接:https://www.haomeiwen.com/subject/bnmovktx.html