DIV CSS 佈局教程網

用 ion-slide-box 做可滑動切換的 tab
編輯:關於JavaScript     

利用 Ionic 的 slide-box 元件做可滑動的 tab,核心是同時監聽 tab 點擊與 slide 頁面滑動這兩件事,讓兩邊的狀態互相同步。搭配 ng-repeat 之後程式碼可以精簡不少。

先看成果:

css:

 .tab_default{ border-bottom:solid 1px #F2F2F2; padding:6px 0; } .tab_select{ border-bottom:solid 1px #3E89F5; box-shadow:0 -3px 8px #C1D3F0 inset; } .arrow-top { position: absolute; width: 0; height: 0; top:20px; border: 6px solid #3E89F5; border-right-color:transparent; border-left-color: transparent; border-top-color: transparent; } .arrow-top:after { content:''; position:absolute; width: 0; height: 0; border: 12px solid #fff; right: -12px; bottom: -13px; border-right-color:transparent; border-left-color: transparent; border-top-color: transparent; }

html:

 <ion-view view-title="滑動tab"> <ion-content has-bouncing="false"> <div style="display:flex;width:100%;"> <div style="flex:1;text-align: center;" class="tab_default" ng-repeat="d in tabNames" ng-click="activeSlide($index)" ng-class="slectIndex==$index ? 'tab_select' : '' "> {{d}} <div class="arrow-top" style="left:{{15+$index*33}}%" ng-show="slectIndex==$index"></div> </div> </div> <ion-slide-box on-slide-changed="slideChanged(index)" active-slide="slideIndex" does-continue="false" show-pager="false"> <ion-slide ng-repeat="p in pages"> <div ng-include="p"></div> </ion-slide> </ion-slide-box> </ion-content> </ion-view> 

controller.js:

 $scope.tabNames=['java','html5','android']; $scope.slectIndex=0; $scope.activeSlide=function(index){//點擊時候觸發 $scope.slectIndex=index; $ionicSlideBoxDelegate.slide(index); }; $scope.slideChanged=function(index){//滑動時候觸發 $scope.slectIndex=index; }; $scope.pages=["templates/tab01.html","templates/tab02.html","templates/tab03.html"]; 

tab01.html、tab02.html、tab03.html 內容大同小異,以 tab01 為例:

 <div style="width:100%;text-align: center;padding-top:30px;"> page 01 <p style="margin-top:30px;"> <img src="img/tab01.jpg" style="width:100%;"/> </p> </div> 

幾個重點:

點擊時把迴圈索引 $index 寫進 slectIndex,再用 ng-class 比對兩者是否相同,相同就套用高亮樣式;滑動時則由 on-slide-changed 回傳的 index 更新同一個變數。兩個方向寫入同一個狀態變數,tab 與 slide 自然就同步了。

箭頭位置用 left:{{15+$index*33}}% 即興算了一個百分比,這種寫法在 tab 數量固定時很省事,但日後若要擴充欄位數,記得改回由 computed style 動態計算,否則對位會歪。

如果只想點擊、不想滑動,可以移除 on-slide-changed 的監聽,或者加上 disable-scroll="true" 直接禁止滑動手勢。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved