直接以750px設計稿為例:
(function(designWidth, maxWidth) { var doc = document, win = window; var docEl = doc.documentElement; var remStyle = document.createElement("style"); //獲取基準字體大小 function refreshRem() { // var width = parseInt(window.screen.width); // uc有bug var width = docEl.getBoundingClientRect().width; if (!maxWidth) { maxWidth = 750; }; if (width > maxWidth) { width = maxWidth; } var rem = width/designWidth*100; //得到的rem基準字體大小,這里乘以100是為了適配有的瀏覽器不識別小數,會導致設定字體無效, //設定根元素html的字體大小為基準字體大小,在css中每rem就是這個值的大小, remStyle.innerHTML = 'html{font-size:' + rem + 'px;} '; } refreshRem(); if (docEl.firstElementChild) { docEl.firstElementChild.appendChild(remStyle); } else { var wrap = doc.createElement("div"); wrap.appendChild(remStyle); doc.write(wrap.innerHTML); wrap = null; } /* 以下為在不同的時機重新計算rem*/ win.addEventListener("resize", function() { // clearTimeout(tid); //防止執行兩次 // tid = setTimeout(refreshRem, 50); refreshRem() }, false); win.addEventListener("pageshow", function(e) { if (e.persisted) { // 瀏覽器后退的時候重新計算 refreshRem() // clearTimeout(tid); // tid = setTimeout(refreshRem,50); } }, false); })(750, 750);
另外找了兩篇說的比較細的文章,鏈接如下:
https://www.cnblogs.com/hjptopshow/p/9382448.html
https://www.cnblogs.com/Sky-Ice/p/9596420.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/60276.html
標籤:Html/Css
上一篇:移動端性能優化(CSS性能優化)
下一篇:超大解析度螢屏適配方案
