手机页面的一种典型布局方式为:头(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