Page({
data:{
tabListSize: [],
scrollToLeft: '',
scrollAreaLeft: 0,
scrollAreaWidth: 0,
}
onReady: function () {
setTimeout(() => {
this.initScrollData()
}, 300)
},
changeTab(e) {
const { index } = e.currentTarget.dataset;
const { isHot, subCateIdStr, id } = this.data.cateList[index];
this.setData({
currentTab: index,
});
this.scrollDom(index)
},
scrollDom(index) {
if (this.data.tabListSize.length == 0) {
this.initScrollData();
return;
}
const offsetLeft = this.data.tabListSize[index].left - this.data.scrollAreaLeft
const scrollLeft = offsetLeft - (this.data.scrollAreaWidth - this.data.tabListSize[index].width) / 2;
this.setData({
scrollToLeft: scrollLeft < 0 ? 0 : scrollLeft
})
},
initScrollData() {
const query = wx.createSelectorQuery().in(this);
query.select('.tab-list-cateList').fields({
rect: true,
size: true
}, res => {
console.log(res,'resssss--')
this.data.scrollAreaLeft = res.left;
this.data.scrollAreaWidth = res.width;
});
query.selectAll('.tab-item-cateList').fields({
rect: true,
size: true
}, data => {
data.forEach((item, index) => {
console.log(item.width, 'width')
this.data.tabListSize.push({
width: item.width,
left: item.left
});
});
});
query.exec();
},
页面html
<van-sticky offset-top="{{56}}">
<scroll-view scroll-x="true" scroll-with-animation="{{true}}" throttle="{{false}}" scroll-left="{{scrollToLeft}}" >
<view class="tab-list-cateList">
<view wx:for="{{cateList}}" wx:key="id" class="tab-item-cateList {{currentTab==index?'active-tab':''}}" data-index="{{index}}" bindtap="changeTab">{{item.tagName}}</view>
</view>
</scroll-view>
</van-sticky>