(function fn(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 * 75) / designwidth; // (basewidth / designwidth) * screenwidth 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);