類似tabBar的切換頁面效果(微信小程序)
需求分析
微信小程序開發,經常遇到類似tabBar的頁面切換效果:視圖中有標題和頁面,當點擊一個標題時,該標題呈選中狀態,頁面自動切換;當滑動頁面時,標題自動切換。
實現邏輯
這種效果的實現邏輯是:定義變量selectedTitle、標題的id,當id和selectedTitle相等時,定義樣式title-selected。當點擊一個標題時,將該標題的id賦值給selectedTitle,該標題獲得樣式title-selected,呈現選中狀態。頁面使用swiper組件,將current屬性與selectedTitle綁定,可以實現頁面自動切換。將current賦值給selectedTitle,當滑動頁面時,標題將自動切換。
項目源碼
頁面切換-橫向的代碼如下。
1、JS文件
data: { // 定義標題的數組
titles: ["Yellow", "Orange", "Green", "Blue", "Purple"], // 定義選中標題的初始值0
selectedTitle: "0", }, // 定義點擊標題的事件處理函數,將選中標題的id賦值給selectedTitle
bindtap: function (e) { console.log(e) this.setData({ selectedTitle: e.currentTarget.id }); }, //定義滑塊改變的事件處理函數,將current賦值給selectedTitle
bindChange: function (e) { this.setData({ selectedTitle: e.detail.current }) }, onReady: function () { // 頁面渲染完成
var that = this; wx.getSystemInfo({ success: function (res) { that.setData({ swiperHeight: (res.windowHeight - 37) }); } }) }
2、WXML文件
<view class="titles">
<!--綁定事件處理函數bindtap-->
<!--給選中的組件,即數組當前項的下標與selectedTitle相等的組件,定義樣式名titles-selected-->
<block wx:for="{{titles}}">
<view id="{{index}}" bindtap="bindtap" class="title {{index==selectedTitle ? 'title-selected' : ''}}"> {{item}} </view>
</block>
</view>
<!--綁定事件處理函數bindchange-->
<swiper bindchange="bindChange" current='{{selectedTitle}}' style="height:{{swiperHeight}}px">
<block wx:for="{{titles}}">
<swiper-item>
<!--設置5個樣式名-->
<view class='page bc_{{item}}'>{{item}}</view>
</swiper-item>
</block>
</swiper>
3、WXSS文件
.titles {
height: 36px;
width: 750rpx;
background-color: lightgray;
display: flex;
justify-content: space-around;
}
.title {
width: 180rpx;
display: flex;
align-items: center;
justify-content: center;
}
.title-selected {
border-bottom: 2px solid red;
color: red;
}
.page {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
font-size: 90rpx;
color: white;
}
.bc_Yellow {
background-color: yellow;
}
.bc_Orange {
background-color: orange;
}
.bc_Green {
background-color: green;
}
.bc_Blue {
background-color: blue;
}
.bc_Purple {
background-color: purple;
}