移动端适配rem.js

rem.js

(function (doc, win) {
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        recalc = function () {
            var clientWidth = docEl.clientWidth;
            if (!clientWidth) return;
            if (clientWidth >= 750) {
                docEl.style.fontSize = '100px';
            } else {
                docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
            }
            var html = document.getElementsByTagName('html')[0];
            var settedFs = settingFs = parseInt(100 * (clientWidth / 750));
            var whileCount = 0;
            while (true) {
                var realFs = parseInt(window.getComputedStyle(html).fontSize);
                var delta = realFs - settedFs;
                //不相等
                if (Math.abs(delta) >= 1) {
                    if (delta > 0)
                        settingFs--;
                    else
                        settingFs++;
                    html.setAttribute('style', 'font-size:' + settingFs + 'px!important');
                } else
                    break;
                if (whileCount++ > 100)
                    break
            }
        };
    if (!doc.addEventListener) return;
    win.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
View Code

 

使用时,引入rem.js

1rem=100px

用rem代替px写样式

posted @ 2020-11-01 15:52  小白&小菜  阅读(769)  评论(0编辑  收藏  举报
我是一个小菜鸟,飞呀飞呀,快飞高