js动态计算移动端rem适配问题


title: js动态计算移动端rem适配问题
date: 2017-04-20 14:33:37
tags:

  • rem
  • js
  • css3
  • media query

摘要:css3和js是实现rem适配

第一: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字体,例如下面这样

(function (doc, win) {
    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);

以上两种方式均能实现rem适配

猜你喜欢

转载自blog.csdn.net/weixin_41819098/article/details/88054378
今日推荐