微信小程序scroll-view配合swiper实现tab栏切换
**要在小程序里面实现一个tab栏切换的页面 但是tab的数量是动态渲染的 会很多 所有就用了scroll-view超出部分能滑动 下面就用swiper滑动切换 废话不多说 直接贴上代码吧 ** ,
- ##效果图
代码
wxml
// wxml
//tab头部 数据代码请省略 scroll-with-animation="true"添加动画效果很重要 不然scroll-left变换的时候会卡帧**
<scroll-view scroll-x style="width: 100%" class='soloo' scroll-left="{{scrollLeft}}" scroll-with-animation="true">
<view class="tab-item {{currentTab == index ?'active':''}}"
data-current="{{index}}" data-id="{{item.id}}"
bindtap="swichNav" wx:key="listClassify" wx:for="{{listClassify}}" wx:for-index="index">{{item.name}} </view>
</scroll-view>
//下方轮播页面
<swiper class="tab-content" current="{{currentTab}}" duration="300" bindchange="switchTab" style="height:{{winHeight}}rpx">
//请忽略循环数据文代码
<swiper-item wx:for="{{listClassify}}" wx:key='index' >
</swiper-item>
</swiper>
js代码
Page({
/**
* 页面的初始数据
*/
data: {
winHeight: "", //窗口高度
currentTab: 0, //预设当前项的值 //这里可以直接设置swiper对应的下标
scrollLeft:'', //距离左边的距离
clientWidth:'', //屏幕的宽
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
// 高度自适应
wx.getSystemInfo({
success: function(res) {
var clientHeight = res.windowHeight,
clientWidth = res.windowWidth,
rpxR = 750 / clientWidth;
var calc = clientHeight * rpxR - 88;
that.setData({
winHeight: calc,
cityid: cityid,
clientWidth: clientWidth
});
}
});
},
// 滚动切换标签样式
swichNav: function(e) {
var cur = e.target.dataset.current;
if (this.data.currentTab == cur) {
return false;
} else {
this.setData({
currentTab: cur
})
}
},
// 滚动切换标签样式
switchTab: function (e) {
this.setData({
currentTab: e.detail.current
});
this.eady()
this.huoqu(2, that.data.clasifys[e.detail.current]);
},
//获取节点宽度 把之前的相加起来 等于滚动条距离left的距离
//重点设置在这里 设置滚动条的距离
eady:function () {
var self = this;
//获取导航的初始位置
const query = wx.createSelectorQuery()
query.selectAll('.tab-item').boundingClientRect();
query.exec(function (res) {
//遍历你当前的tab栏 之前的所有dom节点的宽 相加设置为滚动条滚去的scrollLeft 就搞定了
var num=0;
for (var i = 0; i < self.data.currentTab;i++){
num += res[0][i].width
}
self.setData({
scrollLeft: Math.ceil(num)
})
})
},
// 下拉到底事件
lower(){
//这里的事件是我做分页加载的
}
})