Nana's Blog

Vuejs项目配置webpack将px自动转化为rem,适配移动端

本项目采用 iPhone 6 物理像素为 750px * 1334px 的设计稿

rem兼容性
先看看rem的兼容性,关于移动端
ios:6.1系统以上都支持
android:2.1系统以上都支持
大部分主流浏览器都支持,可以安心的往下看了

rem基准值计算
iPhone6的屏幕大小是375px,

1
1rem = window.innerWidth  / 10

这样计算出来的rem基准值就是37.5(iphone6的视觉稿),这里为什么要除以10呢,其实这个值是随便定义的,因为不想让html的font-size太大,当然也可以选择不除,只要在后面动态js计算时保证一样的值就可以

动态设置html的font-size

1
2
3
4
5
6
7
window.onresize = setHtmlFontSize
function setHtmlFontSize () {
const htmlWidth = document.documentElement.clientWidth || document.body.clientWidth
const htmlDom = document.getElementsByTagName('html')[0]
htmlDom.style.fontSize = htmlWidth / 10 + 'px'
}
setHtmlFontSize()

但页面很大的时候,我们作的移动适配方案会呈现很大的字体,这不是我们想要的。所以加一个判断,解决页面字体过大的问题。
在 index.html的script里加入判断页面的语句。

1
if ( htmlWidth > 750) { htmlWidth = 750 }

当然我们不能每次设置元素的时候,都要自己去算一下,这样就显得 low 了,有两种解决方案:

  1. 前端构建中,完全可以利用scss来解决这个问题,例如我们可以写一个scss的function px2rem即:
    1
    2
    3
    4
    @function px2rem($px){
    $rem : 37.5px;
    @return ($px/$rem) + rem;
    }

这样,当我们写具体数值的时候就可以写成:

1
2
height: px2rem(90px);
width: px2rem(90px);;

  1. 配置一下webpack,自动转换px为对应的rem值
    配置 postcss-pxtorem 自动转换px为rem
  • 安装 postcss-pxtorem

    1
    npm install postcss-pxtorem -D
  • 修改根目录 .postcssrc.js 文件
    找到 plugins 属性新增pxtorem的设置

    1
    2
    3
    4
    "postcss-pxtorem": {
    "rootValue": 32,
    "propList": ["*"]
    }

按照上述配置项目后,即可在开发中直接使用 px 单位开发。
例如设计给出的设计图是 750 * 1334,那么可以直接在页面中写

1
2
3
4
body {
width: 750px;
height: 1136px;
}

将被转换为

1
2
3
4
body {
widht: 23.4375rem;
height: 35.5rem;
}

注意:

  • 此方法支持import 和 .vue单文件中style。暂不支持style中使用@import url();
  • 怎么才能让某一个属性不转化成rem呢。。。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    // `px` is converted to `rem`
    .convert {
    font-size: 16px; // converted to 1rem
    }

    // `Px` or `PX` is ignored by `postcss-pxtorem` but still accepted by browsers
    .ignore {
    border: 1Px solid; // ignored
    border-width: 2PX; // ignored
    }

大致意思就是说:目前,忽略单个属性的最简单的方法是在像素单元声明中使用大写。
。。。原来这么简单,把px改成Px就行啦,亲测移动端PC端都没有问题。。。
2018080611534166.png

另附配置项详细解释:

autoprefixer: 添加浏览器前缀
postcss-pxtorem:{
rootValue:32: 根大小32
propList: [ ] 属性的选择器,*表示通用
selectorBlackList : [ ] 忽略的选择器 .ig- 表示 .ig- 开头的都不会转换
}