根據iPhone6設計稿動態計算rem值

rem 單位在作移動端的h5開發的時候是最常用的單位。爲解決自適應的問題,咱們須要動態的給文檔的更節點添加font-size 值。使用mediaquery 能夠解決這個問題,可是每個文件都引用一大串的font-size 值很繁瑣,並且值也不能達到連續的效果。設計

就使用js動態計算給文檔的fopnt-size 動態賦值解決問題。code

使用的時候,請將下面的代碼放到頁面的頂部(head標籤內);事件

/**
 * [以iPhone6的設計稿爲例js動態設置文檔 rem 值]
 * @param  {[type]} currClientWidth [當前客戶端的寬度]
 * @param  {[type]} fontValue [計算後的 fontvalue值]
 * @return {[type]}     [description]
 */
<script>
    var currClientWidth, fontValue,originWidth;
    //originWidth用來設置設計稿原型的屏幕寬度(這裏是以 Iphone 6爲原型的設計稿)
    originWidth=375;
    __resize();

    //註冊 resize事件
    window.addEventListener('resize', __resize, false);

    function __resize() {
        currClientWidth = document.documentElement.clientWidth;
        //這裏是設置屏幕的最大和最小值時候給一個默認值
        if (currClientWidth > 640) currClientWidth = 640;
        if (currClientWidth < 320) currClientWidth = 320;
        //
        fontValue = ((62.5 * currClientWidth) /originWidth).toFixed(2);
        document.documentElement.style.fontSize = fontValue + '%';
    }
    </script>
相關文章
相關標籤/搜索