导航栏滚动居中
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201207190917367.png)
wxml
<view class="content">
<scroll-view scroll-x="true" scroll-with-animation style="width:100%;" class="ul" scroll-left="{{scrollLeft}}">
<view wx:for="{{8}}" wx:key="index" class="li strategy-tab {{currentIndex == index ? 'active':''}}"
data-index="{{index}}" catchtap="liClick">可爱{{index}}</view>
</scroll-view>
</view>
JS
// pages/component/nav/nav.js
Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
scrollLeft: 0,
currentIndex: 0
},
/**
* 组件的方法列表
*/
methods: {
liClick(e) {
let { index } = e.currentTarget.dataset
let offsetLeft = e.currentTarget.offsetLeft
this.setData({ currentIndex: index })
this.playCenter(offsetLeft, index)
},
// 点击导航栏滚动
playCenter(offsetLeft, index) {
var that = this;
const winweight = wx.getSystemInfoSync().windowWidth;
const query = wx.createSelectorQuery().in(this);
query
.selectAll(`.strategy-tab`)
.boundingClientRect(rect => {
that.setData({
scrollLeft: offsetLeft - winweight / 2 + rect[index].width / 2
});
})
.exec();
},
}
})