【rem】自定義rem.js
阿新 • • 發佈:2018-12-23
console.time("test"); !function(win, option) { var count = 0, designWidth = option.designWidth, designHeight = option.designHeight || 0, designFontSize = option.designFontSize || 20, callback = option.callback || null, root = document.documentElement, body = document.body, rootWidth, newSize, t, self; root.style.width = '100%'; //返回root元素字型計算結果 function _getNewFontSize() { var scale = designHeight !== 0 ? Math.min(win.innerWidth / designWidth, win.innerWidth / designWidth) : win.innerWidth / designWidth; return parseInt( scale * 10000 * designFontSize ) / 10000; } !function () { rootWidth = root.getBoundingClientRect().width; self = self ? self : arguments.callee; //如果此時螢幕寬度不準確,就嘗試再次獲取解析度,只嘗試20次,否則使用win.innerWidth計算 if( rootWidth !== win.innerWidth && count < 20 ) { win.setTimeout(function () { count++; self(); }, 0); } else { newSize = _getNewFontSize(); //如果css已經相容當前解析度就不管了 if( newSize + 'px' !== getComputedStyle(root)['font-size'] ) { root.style.fontSize = newSize + "px"; return callback && callback(newSize); }; }; }(); //橫豎屏切換的時候改變fontSize,根據需要選擇使用 win.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function() { clearTimeout(t); t = setTimeout(function () { self(); }, 300); }, false); }(window, { designWidth: 375, designHeight: 640, designFontSize: 10, callback: function (argument) { console.timeEnd("test") } });