微信小程序解決swiper組件高度問題(可實(shí)現(xiàn)不同tab欄,swiper組件不同高度)
前言
我們經(jīng)常會(huì)使用微信小程序自帶的tab組件與swiper組件搭配來實(shí)現(xiàn)漂亮的tab切換頁(yè)面,但是我們不得不承認(rèn)swiper組件默認(rèn)高度的確是很讓我們頭疼。那么下面我們來實(shí)現(xiàn)上圖中根據(jù)不同的tab頁(yè)面來使swiper頁(yè)面動(dòng)態(tài)的變換高度。
干貨
wxml
<!--index.wxml-->
<view class="container">
<view class="tab-body" hover-class="none" hover-stop-propagation="false">
<view class="tab">
<text class=" {{currentTab==0 ? 'select' : ''}}" data-current="0" bindtap="swichNav">Tab1</text>
<text class=" {{currentTab==1 ? 'select' : ''}}" data-current="1" bindtap="swichNav">Tab2 </text>
<text class=" {{currentTab==2 ? 'select' : ''}}" data-current="2" bindtap="swichNav">Tab3 </text>
</view>
</view>
<swiper current="{{currentTab}}" bindchange="bindChange" class='swp' style="height:{{swiperViewHeight}}px">
<swiper-item>
<view class="v1">
<view class="box"></view>
<view class="box2"></view>
</view>
</swiper-item>
<swiper-item>
<view class="v2">
<view class="box"></view>
<view class="box1"></view>
<view class="box2"></view>
</view>
</swiper-item>
<swiper-item>
<view class="v3">
<view class="box"></view>
<view class="box2"></view>
<view class="box1"></view>
<view class="box2"></view>
<view class="box"></view>
<view class="box1"></view>
</view>
</swiper-item>
</swiper>
</view>
wxss
.swp{
width: 100%;
height: 100%;
padding-top: 80rpx;
}
page{
height: 100%;
background:#f4f4f4;
}
.select{
color: blue;
}
.tab-body{
position: fixed;
top:0;
width: 100%;
z-index: 100;
background: #dddddd;
}
.tab{
display:flex;
justify-content:space-around;
}
.box{
width:50%;
height: 500rpx;
margin:0 auto;
background:green;
}
.box1{
width:50%;
height: 500rpx;
margin:0 auto;
background:red;
}
.box2{
width:50%;
height: 500rpx;
margin:0 auto;
background:orange;
}
index.js
Page({
data:{
currentTab: 0,
swiperViewHeight: '',
arr:['.v1','.v2','.v3']
},
// 滑動(dòng)切換
bindChange: function (e) {
var that = this;
that.setData({
currentTab: e.detail.current
});
this.setSwiperHeight(this.data.arr[e.detail.current])
},
//點(diǎn)擊tab切換
swichNav: function (e) {
var that = this;
if (this.data.currentTab === e.target.dataset.current) {
return false;
} else {
that.setData({
currentTab: e.target.dataset.current
})
}
},
// 賦值高度
setSwiperHeight: function (v) {
let query = wx.createSelectorQuery().in(this);
query.select(v).boundingClientRect();
query.exec((res) => {
let headerHeight = res[0].height;
this.setData({
swiperViewHeight: headerHeight
});
});
},
// swiper 自適應(yīng)高度
onLoad: function (options) {
this.setSwiperHeight(this.data.arr[0])
},
})
講解
其實(shí)這里核心解決方法就是動(dòng)態(tài)獲取每個(gè)tab頁(yè)面的高度,使用了微信小程序自帶的api來獲取容器的高度。通過觸發(fā)tab欄來獲取對(duì)應(yīng)的頁(yè)面高度,達(dá)到不同tab欄不同容器高度效果。
作者:Vam的金豆之路
主要領(lǐng)域:前端開發(fā)
我的微信:maomin9761
微信公眾號(hào):前端歷劫之路