JS 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
(function (doc, win) {
var docEl = doc.documentElement,
resizeEvt = "orientationchange" in window ? "orientationchange" : "resize",
recalc = function () {
var clientWidth = docEl.clientWidth;
if (!clientWidth) return;

//当小于640的时候,采用640的设计稿
//if(clientWidth < 640) {
// fontSize = 20/640*clientWidth;
//当大于640的时候,采用1246的设计稿
//} else {
// fontSize = 20/1246*clientWidth;
//}

docEl.style.fontSize = (20 / 640) * clientWidth + "px"; //【注释1】
};

if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener("DOMContentLoaded", recalc, false);
})(document, window);

注释 1:设置 body 的 font-size

假设设计稿为 640px,基础像素为 20

1
2
3
640(设计图宽)   font-size:20px(body基础像素)
———————————— = ———————————————————————————— = 1rem
doc(实际宽度) font-size:Xpx(求body像素大小)

理解:
640 的时候,1rem = 20px
doc 的时候,1rem = Xpx
都是 1rem,所以是等比缩放的

less 单位 (求 1px=?)

@px:1/20rem; //1rem = 20px 所以 1px=1/20rem
以后就可以直接用*@px 来代替 px 单位了-这一步的目的是为了使数值和设计稿的数值统一,不用换算

当还有一个 750 设计图的时候,求此时 1px=多少 rem
注意:750 的稿 1px 就不是 1rem 了,求得就是这个 xrem

1
2
3
4
5
6
7
8
9
640   29px
——— = ———— = 1rem
750 Xpx

20*750
Xpx = ————————— px = 1rem
640

1px = 640/(20*750)rem

流媒体

通过上述自适应不影响媒体查询

兼容华为

1
2
3
4
5
6
7
8
9
10
11
12
function refreshRem() {
var width = docEl.getBoundingClientRect().width;

var fontSize = width / 10;
docEl.style.fontSize = fontSize + "px";

var effectSize = parseFloat(getComputedStyle(docEl).fontSize);
if (effectSize !== fontSize) {
// fix:华为荣耀、魅族m1 note、三星Note4等手机内置webview会自动对设置的font-size乘一个系数,导致页面偏大(Font Boosting)
docEl.style.fontSize = (fontSize * fontSize) / effectSize + "px";
}
}
← Prev Next →