REM布局-自动计算根fontsize

/* 根据窗口宽度自动计算html基准字体大小,用于移动端弹性布局 */
(function() {
    var docEl = document.documentElement,
        docBody = document.body,
        baseFontSize = 100,//为了方便,这样rem=px/100
        pageMaxWidth = 750,
        rootHtml = document.getElementsByTagName('html')[0],
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        recalc = function() {
            var clientWidth = clientWidth = docEl.clientWidth || docBody.clientWidht;

            //最大宽度显示为750的宽度
            if (clientWidth > pageMaxWidth) {
                clientWidth = pageMaxWidth
            }

            if (!clientWidth) return;
            rootHtml.style.fontSize = baseFontSize * (clientWidth / pageMaxWidth) + 'px';
        };
    if (!window.addEventListener) return;

    window.addEventListener(resizeEvt, recalc, false);

    recalc();
})();

你可能感兴趣的:(REM布局-自动计算根fontsize)