1.相对于比较简单的rem
function rem() {
document.documentElement.style.fontSize = document.documentElement.clientWidth / 7.5 + "px";
}
rem();
window.onresize = rem;
2.相对于比较详细的设置rem
(function(doc, win) {
var docEl = doc.documentElement,
resizeRem = 'orientationChange' in window ? 'orientationChange' : 'resize';
function handle() {
if (docEl.clientWidth > 750) {
docEl.style.fontSize = '100px';
} else {
docEl.style.fontSize = docEl.clientWidth / 7.5 + 'px';
}
}
handle()
if (!doc.addEventListener) return;
window.addEventListener(resizeRem, handle, false);
})(document, window)
详述分析rem
(function(doc, win) {
var doc1 = doc.documentElement; //获取文档的根节点
function handle() {
// if (doc1.clientWidth > 750) { //根据document的可视宽度,当屏幕大于750的时候
// doc1.style.fontSize = '100px'; //根元素 移动端的屏幕不可能大于750的所以必然会执行else
// } else {
// doc1.style.fontSize = doc1.clientWidth / 7.5 + 'px'; //把当前document的可视宽度除7.5,然后重新赋给document的字体大小
// }
doc1.style.fontSize = doc1.clientWidth / 7.5 + 'px';//适应任何屏幕大小,可以无限放大,没有屏幕大小的标准
};
handle();//函数调用
if (doc.addEventListener){//判断文档的根节点
doc.addEventListener('resize', handle, false);
}
window.addEventListener('resize', handle, false); //监听屏幕大小发生变化 调用函数禁止捕获
})(document, window);