配置项目移动端自适应
-
配置rem
-
淘宝方案
- https://github.com/amfe/lib-flexible
/* 通过js来动态添加rem */ ;(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); } })(375, 750); // 备注: 这里的375本身就应该写成750 ,但是写成750之后,我们设计稿的尺寸要/50,不好算,我就想,除以100更好算,所以我改成了375
-
网易方案
function font () { document.documentElement.style.fontSize = document.documentElement.clientWidth / 3.75 + 'px' } font() window.onresize = font
-
阿里rem
(function(doc, win) { const docEl = doc.documentElement, resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize', recalc = function() { const clientWidth = docEl.clientWidth; if (!clientWidth) return; let max = 24; let min = 9.3125; let size = 20 * (clientWidth / 320); size = Math.min(size, max); size = Math.max(size, min); docEl.style.fontSize = size + 'px'; console.log(docEl.style.fontSize, 'em= =====') }; if (!doc.addEventListener) return; win.addEventListener(resizeEvt, recalc, false); doc.addEventListener('DOMContentLoaded', recalc, false); })(document, window);
-