rem是什么?
rem(font size of the root element)是指相对于根元素的字体大小的单位。简单的说它就是一个相对单位。看到rem大家一定会想起em单位,em(font size of the element)是指相对于父元素的字体大小的单位。
同样rem也有很多实现方式,不过都是根据rem特性,基于根(html)的font-size大小来做,我见过很多页面 font-size:62.5% 到现在不知道这个是怎么玩的。
rem相对于根(html)的font-size大小来计算
例如:font-size:10px;,那么(1rem = 10px)了解计算原理后
首先解决怎么在不同设备上设置html的font-size大小。
在查看了很多相关rem文章和自己经验后。基本实现原理有两种
1、js 来获取设备宽度。
既然是移动端,我们可以开心的直接不考虑 微软家那几个老儿子
获取设备宽度 rectObject = object.getBoundingClientRect();
返回值是一个DOMRect对象,这个对象是由该元素的 getClientRects() 方法返回的一组矩形的集合, 即:是与该元素相关的CSS 边框集合 。
document.querySelector('.box').getBoundingClientRect();
ClientRect {
bottom: 108
height: 100
left: 8
right: 68
top: 8
width: 60
}
这样就能拿到设备的宽度 当然meta 先设置!!
meta标签
<meta
name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0 minimal-ui"
/>
这样写的原因是为了设置设备的相对于px的宽度
干货!!!
这段代码会自动创建meta,省去不少事,可以粘贴直接用(来源:淘宝)
(function(win) {
var ratio,
scaleValue,
renderTime,
document = window.document,
docElem = document.documentElement,
vpm = document.querySelector('meta[name="viewport"]');
if (vpm) {
var tempArray = vpm
.getAttribute("content")
.match(/initial\-scale=(["']?)([\d\.]+)\1?/);
if (tempArray) {
scaleValue = parseFloat(tempArray[2]);
ratio = parseInt(1 / scaleValue);
}
} else {
vpm = document.createElement("meta");
vpm.setAttribute("name", "viewport");
vpm.setAttribute(
"content",
"width=device-width, initial-scale=1, user-scalable=no, minimal-ui"
);
docElem.firstElementChild.appendChild(vpm);
}
win.addEventListener(
"resize",
function() {
clearTimeout(renderTime);
renderTime = setTimeout(initPage, 300);
},
false
);
win.addEventListener(
"pageshow",
function(e) {
e.persisted &&
(clearTimeout(renderTime),
(renderTime = setTimeout(initPage, 300)));
},
false
);
"complete" === document.readyState
? (document.body.style.fontSize = 12 * ratio + "px")
: document.addEventListener(
"DOMContentLoaded",
function() {
document.body.style.fontSize = 12 * ratio + "px";
},
false
);
initPage();
function initPage() {
var htmlWidth = docElem.getBoundingClientRect().width;
htmlWidth / ratio > 540 && (htmlWidth = 540 * ratio);
win.rem = htmlWidth / 16;
docElem.style.fontSize = win.rem + "px";
}
})(window);
16只是当前项目适合的切分方法,可以根据需要自行调整