微信小程序tab切换加联动,就像有些app中的tab切换
时时不能忘记在微信小程序中是数据驱动,要实现这种效果还是需要从数据入手
属性名 | 类型 | 说明 |
---|---|---|
scroll-left | Number | 设置横向滚动条位置 |
属性名 | 类型 | 说明 |
---|---|---|
current | Number | 当前所在滑块的 index |
<!--index.wxml-->
<scroll-view scroll-x class='scroll-container' scroll-left="{{scroll_left}}">
<view wx:for="{{item}}" wx:key="index" class="toptabbox">
<text bindtap='tabchange' class="toptab {{currentindex==index?'on':''}}" data-current="{{index}}">{{item.text}}</text>
</view>
</scroll-view>
<swiper bindchange='changeview' current="{{currentindex}}" class='swiper-container'>
<swiper-item wx:for="{{item}}" wx:key="index" classs="swiper-item">
<view class='swiper-item-con' style="background:{{item.color}};">{{item.text}}</view>
</swiper-item>
</swiper>
/*index.js*/
Page({
data: {
currentindex: 0,
scroll_left: 0,
item: [
{ "cid": 'c001', "text": "首页", "color": "#d5bb96" },
{ "cid": 'c002', "text": "推荐", "color": "#a696d5" },
{ "cid": 'c003', "text": "视频", "color": "#ce96d5" },
{ "cid": 'c004', "text": "体育", "color": "#a396d5" },
{ "cid": 'c005', "text": "新闻", "color": "#d5bb96" },
{ "cid": 'c006', "text": "科技", "color": "#d596c5" },
{ "cid": 'c007', "text": "军事", "color": "#d5ac96" },
{ "cid": 'c008', "text": "百科", "color": "#d5bb96" },
{ "cid": 'c009', "text": "小知识", "color": "#96b1d5" },
{ "cid": 'c010', "text": "生活", "color": "#96d5a6" },
{ "cid": 'c011', "text": "问答", "color": "#d5bb96" }
],
},
changeview: function (e) {
var current_tap = e.detail.current;
var s = 0;
/*此处选择7为临界点是点前面的7不需要scroll滑动*/
if (current_tap>=7) {
s = parseInt(current_tap-7) * 60;
}
this.setData({
currentindex: e.detail.current,
scroll_left: s
});
},
tabchange: function (e) {
var current_swiper = e.currentTarget.dataset.current;
var s = 0;
if (current_swiper >= 7) {
console.log(current_swiper)
s = parseInt(current_swiper-7) * 60;
}
this.setData({
currentindex: current_swiper,
scroll_left: s
});
}
})
/*index.wxss*/
page{
width:100%;
height:100%;
padding-top:70rpx;
box-sizing: border-box;
}
.on{
color:#ff0000;
border-bottom:1px solid #ff0000;
}
.scroll-container{
height:70rpx;
width:750rpx;
white-space: nowrap;/*必须设置的css属性*/
position: fixed;
top:0;
left:0;
}
.toptabbox{
height:100rpx;
margin:0 12rpx 10rpx;
display:inline-block;/*确实很重要用float好像不行*/
}
.toptab{
width:100%;
height:60rpx;
text-align:center;
font-size:30rpx;
line-height:60rpx;
}
.swiper-container{
color:#fff;
font-size:28rpx;
height:100%;
}
.swiper-item{
width:750rpx;
height:100%;
color:#fff;
}
.swiper-item-con{
text-align: center;
height:100%;
display: flex;
justify-content: center;
align-items: center;
}
注:数据绑定,特别是怎么动态绑定class,控制选中或者未选中状态,其中,绑定class或者style都和vue中的格式不太一样