简单的rem布局解决H5页面适配问题
2019-01-31 本文已影响0人
chenjundi
rem
布局是直接通过动态计算页面宽度从而设置html
根字体大小。
直接上代码:
(function () {
function w() {
/*document.documentElement.style.fontSize = document.documentElement.clientWidth / 7.5 + "px";*/
var r = document.documentElement; //根元素html
var a = r.clientWidth;
//按照750的设计稿换算
if (a > 750) {
a = 750;
}
rem = a / 7.5;
r.style.fontSize = rem + "px";
}
var t;
w();
window.addEventListener("resize", function () {
clearTimeout(t);
t = setTimeout(w, 300);
}, false);
})();
需要注意的一点就是这个js文件必须放在<head>
标签中提前计算,如果放在<body>
标签下可能导致DOM
元素的加载顺序问题引起文件失效。
还有别忘了加上<meta name="viewport" content="width=device-width, initial-scale=1.0">
这个标签,这样你在改变页面宽度的时候就能看到<html>
标签在动态计算font-size
了。
参考链接
在iOS系统下如果你想对设备像素比dpr
做更加精细化的处理,可以参考阿里团队的移动适配方案https://github.com/amfe/article/issues/17