rem自适应布局的js代码
1 ; 2 (function (designWidth, maxWidth) { 3 var doc = document, 4 win = window, 5 docEl = doc.documentElement, 6 remStyle = document.createElement("style"), 7 tid; 8 9 function refreshRem() { 10 var width = docEl.getBoundingClientRect().width; 11 maxWidth = maxWidth || 540; 12 width > maxWidth && (width = maxWidth); 13 var rem = width * 100 / designWidth; 14 remStyle.innerHTML = 'html{font-size:' + rem + 'px;}'; 15 } 16 17 if (docEl.firstElementChild) { 18 docEl.firstElementChild.appendChild(remStyle); 19 } else { 20 var wrap = doc.createElement("div"); 21 wrap.appendChild(remStyle); 22 doc.write(wrap.innerHTML); 23 wrap = null; 24 } 25 //要等 wiewport 设置好后才能执行 refreshRem,不然 refreshRem 会执行2次; 26 refreshRem(); 27 28 win.addEventListener("resize", function () { 29 clearTimeout(tid); //防止执行两次 30 tid = setTimeout(refreshRem, 300); 31 }, false); 32 33 win.addEventListener("pageshow", function (e) { 34 if (e.persisted) { // 浏览器后退的时候重新计算 35 clearTimeout(tid); 36 tid = setTimeout(refreshRem, 300); 37 } 38 }, false); 39 40 if (doc.readyState === "complete") { 41 doc.body.style.fontSize = "16px"; 42 } else { 43 doc.addEventListener("DOMContentLoaded", function (e) { 44 doc.body.style.fontSize = "16px"; 45 }, false); 46 } 47 })(750, 750);
注:只需在script标签插入这段代码,将最后的750改成设计图的尺寸;尺寸将 对应的尺寸 / 100 ,单位为rem
<script>
;
(function (designWidth, maxWidth) {
var doc = document,
win = window,
docEl = doc.documentElement,
remStyle = document.createElement("style"),
tid;
function refreshRem() {
var width = docEl.getBoundingClientRect().width;
maxWidth = maxWidth || 540;
width > maxWidth && (width = maxWidth);
var rem = width * 100 / designWidth;
remStyle.innerHTML = 'html{font-size:' + rem + 'px;}';
}
if (docEl.firstElementChild) {
docEl.firstElementChild.appendChild(remStyle);
} else {
var wrap = doc.createElement("div");
wrap.appendChild(remStyle);
doc.write(wrap.innerHTML);
wrap = null;
}
//要等 wiewport 设置好后才能执行 refreshRem,不然 refreshRem 会执行2次;
refreshRem();
win.addEventListener("resize", function () {
clearTimeout(tid); //防止执行两次
tid = setTimeout(refreshRem, 300);
}, false);
win.addEventListener("pageshow", function (e) {
if (e.persisted) { // 浏览器后退的时候重新计算
clearTimeout(tid);
tid = setTimeout(refreshRem, 300);
}
}, false);
if (doc.readyState === "complete") {
doc.body.style.fontSize = "16px";
} else {
doc.addEventListener("DOMContentLoaded", function (e) {
doc.body.style.fontSize = "16px";
}, false);
}
})(750, 750);
</script>