js部分
//写在page外
var screenWidth = wx.getSystemInfoSync().windowWidth;
let itemWidth = screenWidth / 5;//表示窗口横排显示5个item
//点击item时调用scrollLeft方法
scrollLeft() {
let tabList = this.data.tabList
let tabIndex = this.data.tabIndex
let scrollX = itemWidth * tabIndex - itemWidth * 2;
let maxScrollX = (tabList.length + 1) * itemWidth;
if (scrollX < 0) {
scrollX = 0;
} else if (scrollX >= maxScrollX) {
scrollX = maxScrollX;
}
this.setData({
x: scrollX
})
},
//item部分用scroll-view标签
<scroll-view scroll-x scroll-left="{{x}}" scroll-with-animation="true" class="punchCardDoExam_box_tab flex-j-start">
<view class="perfectCourse_tab_box flex-j-start">
<block wx:for="{{tabList}}" wx:key="index">
<view class="perfectCourse_tab_box_item flex {{tabIndex==index?'curTabBg':''}}" data-index="{{index}}" data-type="{{item.bookType}}" bindtap="chooseTab">
{{item.name}}
</view>
</block>
</view>
</scroll-view>
还可以在内容的部分加上触摸滑屏的功能
<view bind:touchstart="touchStart" bind:touchmove="touchMove" bind:touchend="touchEnd">
//内容部分
</view>
var startX, endX;
var moveFlag = true; // 判断执行滑动事件
记得在move() 方法里调用 scrollLeft(),内容部分滑动的时候,上方的横向tab相应的item也会在正中间
// 触屏滑动
move(type) {
if (type == 1) {
if (this.data.tabIndex > 0) {
let tabIndex = this.data.tabIndex;
tabIndex--;
this.setData({
tabIndex: tabIndex
})
}
} else {
if (this.data.tabIndex < this.data.tabList.length - 1) {
let tabIndex = this.data.tabIndex;
tabIndex++;
this.setData({
tabIndex: tabIndex
})
}
}
this.scrollLeft();
},
touchStart: function (e) {
startX = e.touches[0].pageX; // 获取触摸时的原点
moveFlag = true;
},
// 触摸移动事件
touchMove: function (e) {
endX = e.touches[0].pageX; // 获取触摸时的原点
if (moveFlag) {
if (endX - startX > 50) {
this.move(1);
moveFlag = false;
}
if (startX - endX > 50) {
this.move(2);
moveFlag = false;
}
}
},
// 触摸结束事件
touchEnd: function (e) {
moveFlag = true; // 回复滑动事件
},