微信小程序实现tab切换(可滑动切换)
前言
实现效果:
实现思路
其实这个小功能的实现非常简单,只需要通过一个标识控制选项的样式及显示的内容,当我们触发点击或者滑动事件时动态的改变标识的值即可。话不多说,下面直接上实例代码。
wxml 文件
<view>
<!-- Tab布局 -->
<view class=navBox>
<view class=titleBox bindtap=titleClick data-idx=0>
<text class="{
{0 == currentIndex ? fontColorBox : }}">装备</text>
<hr class="{
{0 == currentIndex ? lineBox : notLineBox}}" />
</view>
<view class=titleBox bindtap=titleClick data-idx=1>
<text class="{
{1 == currentIndex ? fontColorBox1 : }}">活动</text>
<hr class="{
{1 == currentIndex ? lineBox : notLineBox}} " />
</view>
</view>
<!-- 内容布局 -->
<swiper class=swiperTtemBox bindchange=pagechange current={
{currentIndex}}>
<swiper-item class=swiperTtemBox>
<view>装备内容</view>
</swiper-item>
<swiper-item class=swiperTtemBox>
<view>活动内容</view>
</swiper-item>
</swiper>
</view>
js文件
const app = getApp()
Page({
data: {
currentIndex: 0, //默认是活动项
},
// 切换swiper-item触发bindchange事件
pagechange: function (e) {
// 通过touch判断,改变tab的下标值
if ("touch" === e.detail.source) {
let currentPageIndex = this.data.currentIndex;
currentPageIndex = (currentPageIndex + 1) % 2;
// 拿到当前索引并动态改变
this.setData({
currentIndex: currentPageIndex,
})
}
},
//点击tab时触发
titleClick: function (e) {
this.setData({
//拿到当前索引并动态改变
currentIndex: e.currentTarget.dataset.idx
})
},
})
wxss 文件
Page {
/* 全局样式 */
background: rgb(244, 245, 249);
height: 100%;
position: fixed;
}
.fontColorBox,
.fontColorBox1 {
/* 文字默认颜色 */
color: black;
}
.navBox {
/* 顶部tab盒子样式 */
width: 100%;
height: 108rpx;
background: white;
display: flex;
align-items: center;
justify-content: center;
}
.navBox view:last-child {
/* 最后一个tab标题的样式 */
padding-left: 20%;
}
.titleBox {
/* 未选中文字的样式 */
color: rgb(168, 170, 175);
font-size: 30rpx;
display: flex;
flex-direction: column;
align-items: center;
}
.lineBox,.notLineBox{
/* 选中及未选中底线共同样式 */
width: 32rpx;
height: 8rpx;
}
.lineBox {
/* 选中底线样式 */
background: rgb(43, 44, 45);
margin-top: 16rpx;
border-radius: 4rpx;
}
.notLineBox {
/* 未选中底线样式 */
background: transparent;
}
.swiperTtemBox {
/* 底部内容样式 */
height: 100vh;
overflow: scroll;
margin: 12rpx 0rpx;
background: white;
font-size: 28rpx;
}
