移动端字体适配方案

本文主要从两方面适配

1.remjs 字体适配

2.postcss pxtorem 字体适配

1.字体适配 REM.JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* rem.js
* 随分辨率变化设置根font-size大小
* 使字体自适应变化
* @author Marong
*/

(function(win) {
let time
const doc = document
const baseSize = 100 // 1rem = 100px
const designWidth = 375
const maxWidth = 750
let width = doc.documentElement.getBoundingClientRect().width
const height = doc.documentElement.clientHeight

// 判断横竖屏状态
let screenVertical = true
if (width <= height) {
screenVertical = true
} else {
screenVertical = false
}

// 设置根字体大小
function setRem() {
if (width > maxWidth) { // 最大宽度
width = maxWidth
}
const rem = screenVertical
? width * baseSize / designWidth // 横屏
: height * baseSize / designWidth // 竖屏
doc.documentElement.style.fontSize = rem + 'px'
}

// 浏览器缩放时
win.addEventListener('resize', function() {
clearTimeout(time) // 防止执行两次
time = setTimeout(setRem, 300)
}, false)

// 浏览器后退的时候重新计算
win.addEventListener('pageshow', function(e) {
if (e.persisted) {
clearTimeout(time)// 防止执行两次
time = setTimeout(setRem, 300)
}
}, false)

setRem()
})(window)

2.PostCss pxtorem

1
2
// main.js
import 'lib-flexible/flexible.js'
1
2
3
4
5
6
7
8
9
10
11
12
// .postcssrc.js
module.exports = {
plugins: {
autoprefixer: {
overrideBrowserslist: ['Android 4.1', 'iOS 7.1', 'Chrome > 31', 'ff > 31', 'ie >= 8']
},
'postcss-pxtorem': {
rootValue: 100,
propList: ['*']
}
}
}