前言
我们经常会使用微信小程序自带的tab组件与swiper组件搭配来实现漂亮的tab切换页面,但是我们不得不承认swiper组件默认高度的确是很让我们头疼。那么下面我们来实现上图中根据不同的tab页面来使swiper页面动态的变换高度。
干货
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']
- },
- // 滑动切换
- bindChange: function (e) {
- var that = this;
- that.setData({
- currentTab: e.detail.current
- });
- this.setSwiperHeight(this.data.arr[e.detail.current])
- },
- //点击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 自适应高度
- onLoad: function (options) {
- this.setSwiperHeight(this.data.arr[0])
- },
- })
讲解
其实这里核心解决方法就是动态获取每个tab页面的高度,使用了微信小程序自带的api来获取容器的高度。通过触发tab栏来获取对应的页面高度,达到不同tab栏不同容器高度效果。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)