WXML
<view>
<scroll-view scroll-x="{{true}}" class="top-nav-container" scroll-left="{{scrollLeft}}">
<block wx:for="{{topNavs}}">
<view class="tab-item {{currentActiveNavIndex == index ? 'active':''}}" data-current-index="{{index}}" bindtap="topNavChange">
{{item}}
</view>
</block>
</scroll-view>
<swiper bindchange="swiperChange" class="swiper-container" current="{{currentActiveNavIndex}}">
<block wx:for="{{topNavs}}">
<swiper-item style="overflow:scroll">
<view>{{item}}</view>
</swiper-item>
</block>
</swiper>
</view>
WXSS
.top-nav-container{
width: 100%;
height: 60rpx;
line-height: 60rpx;
font-size: 14px;
background-color: #CCC;
vertical-align: middle;
white-space: nowrap;
}
.top-nav-container .tab-item{
display: inline-block;
margin: 0rpx 30rpx;
}
.top-nav-container .tab-item.active{
color: rgb(48, 121, 255);
border-bottom: 4rpx solid #F00;
line-height: 52rpx;
}
.swiper-container{
height: calc(100vh - 60rpx);
font-size: 14px;
}
JS
Page({
data: {
/**
* 導航數據
*/
topNavs: ['直播', '推薦', '世界盃', '生活', '萌寵', '娛樂', '遊戲', '常用', '11111', '22222', '3333', '4444', '5555', '6666'],
/**
* 當前激活的當航索引
*/
currentActiveNavIndex: 0,
/**
* 上一個激活的當航索引
*/
prevActiveNavIndex: -1,
/**
* scroll-view 橫向滾動條位置
*/
scrollLeft: 0
},
/**
* 頂部導航改變事件,即被點擊了
* 1、如果2次點擊同一個當航,則不做處理
* 2、需要記錄本次點擊和上次點擊的位置
*/
topNavChange: function (e) {
var nextActiveIndex = e.currentTarget.dataset.currentIndex,
currentIndex = this.data.currentActiveNavIndex;
if (currentIndex != nextActiveIndex) {
this.setData({
currentActiveNavIndex: nextActiveIndex,
prevActiveNavIndex: currentIndex
});
}
},
/**
* swiper滑動時觸發
* 1、prevIndex != currentIndex 表示的是用手滑動 swiper組件
* 2、prevIndex = currentIndex 表示的是通過點擊頂部的導航觸發的
*/
swiperChange: function (e) {
var prevIndex = this.data.currentActiveNavIndex,
currentIndex = e.detail.current;
this.setData({
currentActiveNavIndex: currentIndex
});
if (prevIndex != currentIndex) {
this.setData({
prevActiveNavIndex: prevIndex
});
}
this.scrollTopNav();
},
/**
* 滾動頂部的導航欄
* 1、這個地方是大致估算的
*/
scrollTopNav: function () {
/**
* 當激活的當航小於4個時,不滾動
*/
if (this.data.currentActiveNavIndex <= 3 && this.data.scrollLeft >= 0) {
this.setData({
scrollLeft: 0
});
} else {
/**
* 當超過4個時,需要判斷是向左還是向右滾動,然後做相應的處理
*/
var plus = this.data.currentActiveNavIndex > this.data.prevActiveNavIndex ? 60 : -60;
this.setData({
scrollLeft: this.data.scrollLeft + plus
});
}
console.info(this.data.currentActiveNavIndex, this.data.prevActiveNavIndex, this.data.scrollLeft);
}
})