手機頁面的一種典型佈局方式爲:頭(header)、主體(main)和底(footer),頭和底放一些經常使用的操做,主體部分顯示內容,以下圖:
要達到的效果是header固定在頭部,footer固定在底部,主體部分能夠滾動,實現的思路有以下幾種:css
一、固定位置(fixed)
利用CSS的position:fixed是最直接的方式,分別將header和footer固定在窗口的頂和底。雖然這種方式最簡單直接,可是存在兩個問題:一、中間的主體部分必須爲header和footer預留出空間,不然內容就會被蓋住。若是header和footer的高度已知且固定,能夠經過給主體設置margin解決。若是不是已知的就麻煩了,必需要藉助js進行計算才行,所以這種方式的的靈活性不夠;二、在iOS環境下,若是頁面上有input空間,輸入時調用軟鍵盤會致使fixed失效,footer顯示的位置就亂了(android下沒有問題)。因此,fixed方式雖然看似簡單,用起來問題很多。android
二、絕對位置(absolute)
採用絕對定位就是把header,main和footer都用absolute放在固定的位置上,讓main支持自動滾動,這樣內容多的時候滾動只發生在main裏面,header和footer的位置固定。這種方式的侷限是必須肯定header和footer的高度,若是不肯定須要藉助js,靈活性不夠。ios
三、彈性位置(flex)
彈性佈局能夠根據容器的狀況和設置的規則自動調整子元素的大小,很是適合解決垂直佈局的問題。可是,也有很多坑。第一,彈性佈局有一新(display:flex)一舊(display:box)兩個版本,固然想用新版本,但是android版的微信不支持,好在ios和主流的瀏覽器也都支持老版本,因此就先用老版本吧(只是作了簡單的兼容測試)。第二,當main區域須要滾屏的時候,androi版的微信會致使footer裏的button不能響應點擊事件,直到滾屏到底,才行,彷佛是main把footer覆蓋了(footer一直可見),設置了z-index也無論用。css3
看代碼:web
<div class='flex-frame' ng-controller="myCtrl2"> <header class='flex-bar'> <button class='btn btn-lg btn-default' ng-click="click($event,'buttonA')">buttonA</button> </header> <div class='flex-main'> <div class='flex-main-wrap'> <ul class='list-group'> <li class='list-group-item' ng-repeat="d in data" ng-bind="d"></li> </ul> <input type='text' class='form-control input-lg'> </div> </div> <footer class='flex-bar'> <button class='btn btn-lg btn-default' ng-click="click($event,'button1')">button1</button> <button class='btn btn-lg btn-default' ng-click="click($event,'button2')">button2</button> </footer> </div>
.flex-frame{height:100%;width:100%;background:#eff;display:-webkit-box;-webkit-box-orient:vertical;} .flex-bar{display:-webkit-box;padding:4px;background:#eee;} .flex-bar>button{display:block;-webkit-box-flex:1.0;margin-left:4px;} .flex-bar>button:first-child{margin-left:0;} .flex-main{position:relative;background:#ccc;-webkit-box-flex:1.0;overflow-y:hidden;padding-bottom:80px;} .flex-main-wrap{position:absolute;top:0;bottom:0;left:0;right:0;overflow-y:auto;}
var data = [], i = 0; while (i<30) { data.push('row:' + i); i++; } $scope.data = data; $scope.click = function(event, name) { alert('click ' + name); }
看例子瀏覽器
PS:
一、原本想用main標籤,發現微信的瀏覽器不認識main標籤,就直接用div了。
二、微信裏若是main區域須要滾屏,footer彷佛就會被蓋住,沒法響應點擊事件,不知道確切的緣由是什麼,找到下面這段話不知道是否是緣由。
When the computed value for the overflow property is ‘visible’, ‘scroll’ or ‘auto’, the content may overflow the container. If the computed value for direction is normal, the content will overflow over the right or bottom side. If the computed value for direction is reverse, the content will overflow over the left or top side.
爲了解決這個問題,加了flex-main-wrap進行控制。微信
參考:
https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_Flexible_Box_Layout
http://www.w3.org/TR/2009/WD-css3-flexbox-20090723/ide