自動改變html font-size,實現移動端rem適配


移動端采用rem適配非常方便

比如在iphone6尺寸下,將html font-size 設置為 100px,那么寫css時,只要將尺寸/100 + rem 即可。

在iphone6Plus尺寸下,html font-size會自動調節,兼容多種尺寸的手機

以下是js代碼,復制到你的項目中即可使用

(function(win) {
var ratio, scaleValue, renderTime,
    htmlEle = document.documentElement,
    vpMeta = document.querySelector('meta[name="viewport"]');

if (vpMeta) {
    var tempArr = vpMeta.getAttribute("content").match(/initial\-scale=(["']?)([\d\.]+)\1?/);
    if (tempArr) {
        scaleValue = parseFloat(tempArr[2]);
        ratio = parseInt(1 / scaleValue);
    }
} else {
    vpMeta = document.createElement("meta");
    vpMeta.setAttribute("name", "viewport");
    vpMeta.setAttribute("content", "width=device-width, initial-scale=0.5, user-scalable=no, minimal-ui");
    htmlEle.firstElementChild.appendChild(vpMeta);
    ratio = 2;
}

win.addEventListener("resize", function() {
    clearTimeout(renderTime);
    renderTime = setTimeout(initPage, 300);
}, false);

win.addEventListener("pageshow", function(e) {
    if(e.persisted){
        clearTimeout(renderTime);
        renderTime = setTimeout(initPage, 300)
    }
}, false);

if("complete" === document.readyState){
    document.body.style.fontSize = 12 * ratio + "px";
}else{
    document.addEventListener("DOMContentLoaded", function() {
        document.body.style.fontSize = 12 * ratio + "px";
    }, false);
}

initPage();

function initPage() {
    var htmlWidth = htmlEle.getBoundingClientRect().width;
    htmlWidth / ratio > 768 && (htmlWidth = 768 * ratio);
    win.rem = 100 * (htmlWidth / 375);
    htmlEle.style.fontSize = win.rem + "px";
}
})(window);

代碼分析

如果你設置了meta標簽的視口屬性,則獲取initial-scale縮放比例,如果沒設置,則自動添加。

一般initial-scale為1

  • line 2 獲取屏幕寬度
  • line 3 如果寬度超過768(ipad平板寬度),則不再進行調節
  • line 4、5 設置rem,我以iphone6寬度375設置的,在該尺寸下,rem=100px,如果是其他尺寸,修改375即可

(htmlWidth/375)得到的是縮放比例,在IPHONE6下計算時,不用管html的font-size,直接px/100即算出rem

  • 當頁面改變尺寸,或者初次顯示的時候,執行方法
  • persisted是pageshow事件的屬性,檢測瀏覽器是否讀取緩存,是的話為true

當頁面渲染完后,設置body html-size,防止使用默認樣式的元素出錯


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM