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

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

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

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

 1 /**
 2  * [以iPhone6的設計稿爲例js動態設置文檔 rem 值]
 3  * @param  {[type]} currClientWidth [當前客戶端的寬度]
 4  * @param  {[type]} fontValue [計算後的 fontvalue值]
 5  * @return {[type]}     [description]
 6  */
 7 <script>
 8     var currClientWidth, fontValue,originWidth;
 9     //originWidth用來設置設計稿原型的屏幕寬度(這裏是以 Iphone 6爲原型的設計稿)
10     originWidth=375;
11     __resize();
12 
13     //註冊 resize事件
14     window.addEventListener('resize', __resize, false);
15 
16     function __resize() {
17         currClientWidth = document.documentElement.clientWidth;
18         //這裏是設置屏幕的最大和最小值時候給一個默認值
19         if (currClientWidth > 640) currClientWidth = 640;
20         if (currClientWidth < 320) currClientWidth = 320;
21         //
22         fontValue = ((62.5 * currClientWidth) /originWidth).toFixed(2);
23         document.documentElement.style.fontSize = fontValue + '%';
24     }
25     </script>
相關文章
相關標籤/搜索