移動端的rem:
使用方法:
- 設置html的font-size,根據瀏覽器分辨率縮放
-
- 設置根元素font-size為100px這樣好用的值,不要設為10px這樣的;
- 然后獲取瀏覽器的分辨率,也就是視口寬度,p(比例尺)= 視口寬度/效果圖寬度
- 根元素font-size=100px*p
- 然后來個resize去跟隨瀏覽器大小變化
-
1(function (win){
7 var doc = win.document,
8 html = doc.documentElement,
9 option = html.getAttribute('data-use-rem');
10
11 if( option === null ){
12 return;
13 }
14
15 // defaut baseWidth : 640px;
16 var baseWidth = parseInt(option).toString() === 'NaN' ? 640 : parseInt(option);
17 var grids = baseWidth / 100;
18 var clientWidth = html.clientWidth || 320;
19
20 // set rem first
21 html.style.fontSize = clientWidth / grids + 'px';
22
23 // create testDom
24 var testDom = document.createElement('div');
25 var testDomWidth = 0;
26 var adjustRatio = 0;
27 testDom.style.cssText = 'height:0;width:1rem;';
28 doc.body.appendChild(testDom);
29
30 var calcTestDom = function(){
31 testDomWidth = testDom.offsetWidth;
32 if( testDomWidth !== Math.round(clientWidth / grids) ){
33 adjustRatio = clientWidth/grids/testDomWidth;
34 var reCalcRem = clientWidth*adjustRatio / grids;
35 html.style.fontSize = reCalcRem + 'px';
36 } else{
37 doc.body.removeChild(testDom);
38 }
39 };
40
41 // detect if rem calc is working directly
42 // if not , recalc and set the rem value
43 setTimeout(calcTestDom, 20);
44
45 var reCalc = function(){
46 var newCW = html.clientWidth;
47 if ( newCW === clientWidth ){
48 return;
49 }
50 clientWidth = newCW;
51 html.style.fontSize = newCW*(adjustRatio?adjustRatio:1) / grids + 'px';
52 // if( testDom ) setTimeout(calcTestDom, 20);
53 };
54
55 // Abort if browser does not support addEventListener
56 if (!doc.addEventListener){
57 return;
58 }
59
60 var resizeEvt = 'orientationchange' in win ? 'orientationchange' : 'resize';
61
62 win.addEventListener(resizeEvt, reCalc, false);
63 // detect clientWidth is changed ?
64 doc.addEventListener('DOMContentLoaded', reCalc, false);
65
66 })(window);
上面的是xiaojue寫的一段代碼,其中重要的一部分就是判斷div的大小是否是精確的
說了rem布局,下面來說說百分比布局
百分比柵格化布局:
這里的柵格化布局方法和思路其實都很簡單,就按照bootstrap的思路來,就是將一個容器,寬度一定或100%的,用一個分子去把這個容器分為很多份,bootstrap的方法是用百分比的方法來將這個容器分為n等份,這就是柵格化的思路,其實不難,就看你的思路是怎樣的,實現起來也是不同。以后有機會會深入的學習一些柵格化布局的思想和優秀方法。
上面介紹了兩種移動端布局方法,其實我們總結一下他們的優缺點,rem只能在移動端進行布局,然后等比例的縮放,在pc端還是用px這種慣用的方法去實現比較好,rem並不能實現響應式布局,這是重要的缺點,rem只在移動端起到一個比較好的作用,當然以后的發展會說不定,也可能還有人發明出厲害的設計方案。而百分比的布局,這種方式有一點是有很大問題的,他是無法做到定高的,這是為什么,因為百分比定高,有時候bug很明顯,所以很多人用px定高,這樣不同分辨率的手機會使得顯示不一樣。
