一個三個模塊:頭部、中部、尾部的頁面,使用css
position:absolute;
固定頭尾,中部佔滿屏幕剩餘部分,但有時中間內容過多,溢出,須要滾動顯示內容時,咱們就須要使用滾動條,在pc端只須要加上html
overflow: auto;
便可,可在移動端會出現兼容性問題,通常解決辦法可加上web
overflow: auto;-webkit-overflow-scrolling:touch;
因爲中間內容滑動到頂部或者底部時,會觸發整個頁面的滑動事件,咱們能夠用js阻止頁面默認滑動事件的發生,從而阻止整個頁面的上移或者下移,touchstart事件階段,記錄手指的Y座標startY,touchmove事件階段,算出手指移動距離diffY=e.touches[0].pageY-startY;判斷當div移動到最頂部且手指向下滑動時或者當div滑動到最下面且手指向上滑動時,阻止整個頁面的默認事件發生;touchend階段,移除阻止事件,代碼實現以下:佈局
//判斷是否支持觸摸事件 function isTouchDevice(){ try{ document.createEvent("TouchEvent"); return true; }catch(e){ return false; } } function touchScroll(obj){ if(isTouchDevice()){ var el=obj[0]; var startY=0,diffY=0; var scrollHeight=el.scrollHeight; var bindPreventTouch=function(){ $(document.body).on("touchmove",function(e){ e.preventDefault(); }); }; obj.on('touchstart',function(e){ startY=e.touches[0].pageY; }); obj.on('touchmove',function(e){ diffY=e.touches[0].pageY-startY; if(el.scrollTop===0&&diffY>0){ //到最上面 bindPreventTouch(); }else if((scrollHeight-el.scrollTop-el.offsetHeight)===0&&diffY<0){ //到最下面 bindPreventTouch(); } }); obj.on('touchend',function(e){ $(document.body).off('touchmove'); }); } } touchScroll($("#MyElement"));
佈局元素和樣式:code
<div class="wrap"> <header>頭部</header> <div class="main" id="MyElement"> <div class="mainbox">彈性滾動區域</div> </div> <footer>底部</footer> </div> <style type="text/css"> *{padding: 0;margin: 0;} html,body{height: 100%;} .wrap{width: 100%;} .wrap{width: 100%;height: 100%;position: absolute;top:0;right: 0;bottom: 0;left: 0;overflow: auto;-webkit-overflow-scrolling:touch;} header,footer{height: 40px;line-height: 40px;background-color:#D8D8D8;text-align:center;position: absolute;left: 0;width: 100%;} header{top: 0;} footer{bottom: 0;} .main{position: absolute;z-index: 1;top:40px;bottom: 40px;width: 100%;background-color: #efefef;overflow: auto;} /* 隱藏滾動條 */ /* .main::-webkit-scrollbar{display: none;} */ .mainbox{width:100%;height: 600px;background-image:-webkit-linear-gradient(top, orange, green);} </style>