The rem layout is not displayed properly on some mobile phones

Description of the problem: The width calculated by rem is inconsistent with the width actually displayed on the mobile phone, and the px is used as expected.

Cause: Some Android phones or webviews have adjusted the default font size of the system. At this time, the 20px set on the html root node is no longer 20px, resulting in an error in calculating the rem width.

Solution:

1. Calculate the actual font size:

var actualSize = parseFloat(window.getComputedStyle(document.documentElement)["font-size"]);

2. Calculate the zoom ratio:

var scale = actualSize / rem; //rem为原本设置的根节点字号

3. To keep other elements of the page unaffected, scale rem directly:

var remScaled = rem / scale;

Full code:

;(function(win) {
     var docEl = win.document.documentElement,
         tid;
 
     function refreshRem() {
         var width = docEl.getBoundingClientRect().width;
         var rem = width / 750*100;//以750px为原稿,除以100可得各元素的rem
         docEl.style.fontSize = rem + "px";
         var actualSize = parseFloat(window.getComputedStyle(docEl)["font-size"]);
         if (actualSize !== rem) {
             var remScaled = rem / ( actualSize / rem );
             docEl.style.fontSize = remScaled + "px"
         }
    }
 
     function dbcRefresh() {
         clearTimeout(tid);
         tid = setTimeout(refreshRem, 100)
     }
 
     win.addEventListener("resize", function() { dbcRefresh() }, false);
     win.addEventListener("pageshow", function(e) {
         if (e.persisted) { dbcRefresh() }
     }, false);
     refreshRem();
})(window);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326440252&siteId=291194637