# 简单版
(function (doc, win) {
var docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function () {
var clientWidth = docEl.clientWidth;
if (!clientWidth) return;
if (clientWidth>=750) {
docEl.style.fontSize = '100px';
} else {
// 可能需要四舍五入 Math.round
docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
}
};
if (!doc.addEventListener) return;
var timer = null;
win.addEventListener(resizeEvt,function(){
// resize 节流
clearTimeout(timer);
timer = setTimeout(recalc,200);
}, false);
doc.addEventListener('DOMContentLoaded',recalc, false);
})(document, window);
# 复杂版本
(function (win){
var doc = win.document,
html = doc.documentElement,
option = html.getAttribute('data-use-rem');
// if( option === null ){
// return;
// }
// defaut baseWidth : 750px;
var baseWidth = parseInt(option).toString() === 'NaN' ? 750 : parseInt(option);
// 比例系数
var grids = baseWidth / 100;
// 视口宽度
var clientWidth = html.clientWidth>baseWidth?baseWidth:html.clientWidth;
// set rem first
html.style.fontSize = clientWidth / grids + 'px';
// create testDom
var testDom = document.createElement('div');
var testDomWidth = 0;
var adjustRatio = 0;
testDom.style.cssText = 'height:0;width:1rem;';
doc.body.appendChild(testDom);
var calcAdjustRatio = function(){
testDomWidth = testDom.offsetWidth;
if( testDomWidth !== Math.round(clientWidth / grids) ){
adjustRatio = clientWidth/grids/testDomWidth;
} else {
adjustRatio = 1;
}
doc.body.removeChild(testDom);
};
// 计算偏差比
setTimeout(calcAdjustRatio, 20);
var reCalc = function(){
var newCW = html.clientWidth>baseWidth?baseWidth:html.clientWidth;
if ( newCW === clientWidth ){
return;
}
clientWidth = newCW;
html.style.fontSize = newCW * adjustRatio / grids + 'px';
};
// 如果不能监听 立即调整
if (!doc.addEventListener){
reCalc();
return;
}
var resizeEvt = 'orientationchange' in win ? 'orientationchange' : 'resize';
var timer = null;
win.addEventListener(resizeEvt, function(){
clearTimeout(timer);
timer = setTimeout(reCalc,200)
}, false);
// detect clientWidth is changed ?
doc.addEventListener('DOMContentLoaded', reCalc, false);
})(window);