移动端适配之rem适配

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
!function(window, document) {
function setSize() {
// 设备宽度
let deviceWidth = window.screen.width;
// 设计稿宽度
const baseValue = 750;
// html的字体大小 = (设备宽度 / 设计稿宽度) * 100
document.documentElement.style.fontSize = (deviceWidth / baseValue) * 100 + 'px';
}
// DOM树加载完执行
window.addEventListener("DOMContentLoaded", function() {
setSize();
})
// 屏幕变化执行
window.addEventListener("resize", function() {
setSize();
})
setSize();

}(window, document)

(不同设备的宽度 / 设计稿的尺寸) * 100%

比如设计稿是750px,有个按钮是 590px 换算之后就是 5.9rem

配合 postcss-pxtorem 这个插件一起食用更香噢~