微信小程序上侧可滑动导航栏(详解)
完成图是这样,左右可以滑动:
代码解释
wxml部分如下:
<view class='list'>
<view
wx:for="{{TypeList}}" data-idx="{{index}}"
bindtap="ChangeTab"
class="{{currentTab==index?'active':'select'}}"
>{{ item }}
</view>
</view>
外部list是导航栏框架,css部分是:
.list{
display: flex;
width: 100%;
overflow-y: scroll;
white-space: nowrap;
}
overflow-y: scroll
用于可左右滑动,white-space: nowrap
使其不换行。
内部vue各行解释:
-
wx:for="{{TypeList}}"
为循环读取数组 -
data-idx="{{index}}"
为点击事件传递数据,最终可在e.currentTarget.dataset
获取中,详见博客 -
bindtap="ChangeTab"
点击事件,对应方法:
ChangeTab: function (e) {
var edata = e.currentTarget.dataset.idx;
this.setData({
currentTab: edata
})
},
class="{{currentTab==index?'active':'select'}}"
动态绑定class,将目前点击的绑定active,其余为select,对应css如下:
.select{
height: 100%;
margin:10rpx;
font-size: 35rpx;
}
.active{
height: 100%;
margin:10rpx;
font-size: 35rpx;
color: #333;
font-weight: 700;
border-bottom: solid 8rpx #e5b062;
}
完整代码
wxml:
<view class='list'>
<view
wx:for="{{TypeList}}" data-idx="{{index}}"
bindtap="ChangeTab"
class="{{currentTab==index?'active':'select'}}"
>{{ item }}
</view>
</view>
wxss:
.list{
display: flex;
width: 100%;
overflow-y: scroll;
white-space: nowrap;
}
.select{
height: 100%;
margin:10rpx;
font-size: 35rpx;
}
.active{
height: 100%;
margin:10rpx;
font-size: 35rpx;
color: #333;
font-weight: 700;
border-bottom: solid 8rpx #e5b062;
}
js:
Page({
data: {
TypeList:["推荐","新鲜蔬菜","新鲜水果","家禽蛋品","水产生鲜","美味干货","其他精选"],
currentTab:0,
},
ChangeTab: function (e) {
var edata = e.currentTarget.dataset.idx;
this.setData({
currentTab: edata
})
},