只需在页面引入这段原生js代码就可以了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
(function (doc, win) {
var
docEl = doc.documentElement,
resizeEvt =
'orientationchange'
in
window ?
'orientationchange'
:
'resize'
,
recalc = function () {
var
clientWidth = docEl.clientWidth;
if
(!clientWidth)
return
;
if
(clientWidth>=640){
docEl.style.fontSize =
'100px'
;
}
else
{
docEl.style.fontSize = 100 * (clientWidth / 640) +
'px'
;
}
};
if
(!doc.addEventListener)
return
;
win.addEventListener(resizeEvt, recalc,
false
);
doc.addEventListener(
'DOMContentLoaded'
, recalc,
false
);
})(document, window);
|
如何使用?
这是rem布局的核心代码,这段代码的大意是:
如果页面的宽度超过了640px,那么页面中html的font-size恒为100px,否则,页面中html的font-size的大小为: 100 * (当前页面宽度 / 640)
为什么是640px?
设计图一般是640px的,这样相当于100px = 1rem,可以方便计算;
因为是640px所以应限制下页面的大小,所以最外层的盒子应该是:
1
2
3
4
5
|
position: relative;
width: 100%;
max-width: 640px;
min-width: 320px;
margin: 0 auto;
|
公司案例:
(function (doc, win) {
"use strict";
var docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function () {
var clientWidth = docEl.clientWidth>800?800:docEl.clientWidth;
var htmlFontSize = 20;
var designWidth = 375;
if (!clientWidth) return;
docEl.style.fontSize = htmlFontSize * (clientWidth / designWidth) + 'px';
var reality = Number(docEl.style.fontSize.substr(0, docEl.style.fontSize.length - 2));
var theory = htmlFontSize * (clientWidth / designWidth);
// alert(reality);
// alert(theory);
if (reality != theory) {
docEl.style.fontSize = htmlFontSize * theory / reality * (clientWidth / designWidth) + 'px';
}
console.log(window.navigator);
console.log("字体大小:" + docEl.style.fontSize);
drawWithCanvas();
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);