px 单位转 rem(移动端适配)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 按照宽度1920或高度1040去换算(1px===1rem)
function setSize() {
let screenWidth = document.documentElement.clientWidth
let screenHeight = document.documentElement.clientHeight
let scaled = 1920 / 1040
let currentFontSize = 12
if (scaled > screenWidth / screenHeight) {
currentFontSize = screenWidth / 1920
} else {
currentFontSize = screenHeight / 1040
}

document.documentElement.style.fontSize = currentFontSize + 'px'
}

(function (w) {
w.addEventListener('resize', setSize)
w.addEventListener('pageShow', setSize)
w.addEventListener('DOMContentLoaded', setSize)
})(window)
setSize()

建议使用上面的方案

1
2
3
4
5
6
7
8
9
10
!function() {
function rem() {
let width = document.documentElement.clientWidth || document.body.clientWidth;
document.documentElement.style.fontSize = width / 7.5 + 'px';
//设置body字体大小,不影响body内字体大小
document.body.style.fontSize = '12px';
}
rem();
window.addEventListener('resize', rem, false);
}();