rem页面布局原理详细解说

何为rem?

相对于根元素(即html元素)font-size计算值的倍数。

通俗的说,1rem = html的font-size值

例如,下这段代码。a标签的font-size值为0.5rem,实际就是100px*0.5=50px。

html{
    font-size:100px;
}
a{
    font-size:.5rem;
}

如何使用rem进行布局?

  1. 标签的rem单位的值怎么计算

通过使用  rem  +   js  改变html标签的font-size(整体缩放)实现兼容性更高的页面

下面来举个例子,

当我们拿到的设计图是750px的时候,窗口宽度750px,html的font-size的大小为100px;

也就是说1rem = 100px;所以标题的font-size的大小为26/100=.26rem;

 

h3{
    font-size:.26rem;
}

  2. 如何实现兼容各种屏幕大小的设备

使用到javascript来动态改变html标签font-size的大小,其他的rem单位的数值就会被浏览动态计算转为px单位,从而达到和设计图高度的相似。

当屏幕750px的时候,html的font-size值是100px;窗口大小变化的时候,可以通过js获取到窗口大小。

这时候获取到一个比例

          750:100=获取到的屏幕大小:html标签的px单位的值

以下js代码,用于实现根据获取到的屏幕大小,动态修改html标签的px单位的值

;(function(designWidth, maxWidth) {
    var doc = document,
        win = window;
    var docEl = doc.documentElement;
    var tid;
    var rootItem,rootStyle;

    function refreshRem() {
        var width = docEl.getBoundingClientRect().width;
        if (!maxWidth) {
            maxWidth = 640;
        };
        if (width > maxWidth) {
            width = maxWidth;
        }
        var rem = width * 100 / designWidth;
        //兼容UC开始
        rootStyle="html{font-size:"+rem+'px !important}';
        rootItem = document.getElementById('rootsize') || document.createElement("style");
        if(!document.getElementById('rootsize')){
        document.getElementsByTagName("head")[0].appendChild(rootItem);
        rootItem.id='rootsize';
        }
        if(rootItem.styleSheet){
        rootItem.styleSheet.disabled||(rootItem.styleSheet.cssText=rootStyle)
        }else{
        try{rootItem.innerHTML=rootStyle}catch(f){rootItem.innerText=rootStyle}
        }
        //兼容UC结束
        docEl.style.fontSize = rem + "px";
    };
    refreshRem();

    win.addEventListener("resize", function() {
        clearTimeout(tid); //防止执行两次
        tid = setTimeout(refreshRem, 300);
    }, false);

    win.addEventListener("pageshow", function(e) {
        if (e.persisted) { // 浏览器后退的时候重新计算
            clearTimeout(tid);
            tid = setTimeout(refreshRem, 300);
        }
    }, false);

    if (doc.readyState === "complete") {
        doc.body.style.fontSize = "16px";
    } else {
        doc.addEventListener("DOMContentLoaded", function(e) {
            doc.body.style.fontSize = "16px";
        }, false);
    }
})(750, 750);

猜你喜欢

转载自www.cnblogs.com/mingmliang/p/9025387.html