;(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);
rem=px/50;css
html { font-size:20px } @media only screen and (min-width:400px) { html { font-size:21.33333333px!important } } @media only screen and (min-width:414px) { html { font-size:22.08px!important } } @media only screen and (min-width:480px) { html { font-size:25.6px!important } }
rem=px/20html