js动态计算移动端rem适配

5次阅读

共计 885 个字符,预计需要花费 3 分钟才能阅读完成。

第一:css3 的 media query 来实现适配,例如下面这样:

html {font-size : 20px;}
@media only screen and (min-width: 401px){
    html {font-size: 25px !important;}
}
@media only screen and (min-width: 428px){
    html {font-size: 26.75px !important;}
}
@media only screen and (min-width: 481px){
    html {font-size: 30px !important;}
}
@media only screen and (min-width: 569px){
    html {font-size: 35px !important;}
}
@media only screen and (min-width: 641px){
    html {font-size: 40px !important;}
}

第二通过 js 动态设置 html 字体,例如下面这样

    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        recalc = function () {
            var clientWidth = docEl.clientWidth;
            if (!clientWidth) return;
           // 默认设计图为 640 的情况下 1rem=100px;根据自己需求修改
            if(clientWidth>=640){docEl.style.fontSize = '100px';}else{docEl.style.fontSize = 100 * (clientWidth / 640) + 'px';
            }
        };

    if (!doc.addEventListener) return;
    win.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);

正文完
 0