響應式佈局想法和實現

看過這篇文章,寫的挺全面, 從幾個方面分析響應式寫法優劣,先收藏:html

http://caibaojian.com/web-app-rem.htmlweb

最終方案:瀏覽器

rem是經過根元素進行適配的,網頁中的根元素指的是html,咱們經過設置html的字體大小就能夠控制rem的大小。app

下面函數將屏幕寬度和根元素字體大小聯繫起來,而頁面內元素寬度都是經過rem來設置,如750頁面最大寬度也就是7.5rem,字體16px =>0.16rem。函數

頁面大小變化時,根元素html大小相應變化,內部元素隨rem變化相應改變,來達到響應效果。字體

//designWidth:設計稿的實際寬度值,須要根據實際設置
//maxWidth:製做稿的最大寬度值,須要根據實際設置
//這段js的最後面有兩個參數記得要設置,一個爲設計稿實際寬度,一個爲製做稿最大寬度,例如設計稿爲750,最大寬度爲750,則爲(750,750)
(function(designWidth, maxWidth) {
    var doc = document,
    win = window,
    docEl = doc.documentElement,
    remStyle = document.createElement("style"),
    tid;

    function refreshRem() {
        var width = docEl.getBoundingClientRect().width;
        maxWidth = maxWidth || 540;
        width>maxWidth && (width=maxWidth);
        var rem = width * 100 / designWidth;
        remStyle.innerHTML = 'html{font-size:' + rem + 'px;}';
    }

    if (docEl.firstElementChild) {
        docEl.firstElementChild.appendChild(remStyle);
    } else {
        var wrap = doc.createElement("div");
        wrap.appendChild(remStyle);
        doc.write(wrap.innerHTML);
        wrap = null;
    }
    //要等 wiewport 設置好後才能執行 refreshRem,否則 refreshRem 會執行2次;
    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);

 擴展閱讀:https://www.cnblogs.com/tiger95/p/7941341.html (3個方案:1.rem 625%  2.網易  3.淘寶)spa

相關文章
相關標籤/搜索