在项目中遇到点击scroll-view中每一项使其居中,查看文档后发现有scroll-view有属性scroll-into-view能够根据id来定位每一项,可是没法居中,因而我想到了使用scroll-left来计算滚动距离是使一项居中.函数
<scroll-view class="power-view" scroll-x="true" scroll-with-animation="true" scroll-left="{{scrollLeft}}" bindscroll="scrollMove">
<block wx:for="{{powerList}}" wx:key>
<view class="item {{index == activeIdx?'active':''}}" bindtap="chooseSub" id="v{{index}}" data-index="{{index}}">
<view class="icon"></view>
<view class="text">整年海量优惠</view>
</view>
</block>
</scroll-view>复制代码
data: {
powerList: ['v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8', 'v9', 'v10', 'v11', 'v12'],
activeIdx: 0, //选中的index
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let scrollInfo = {
prevDistance: 0, //滚动条的距离(默认为0)
screenHalfwidth: wx.getSystemInfoSync().windowWidth / 2,
}
this.data.scrollInfo = scrollInfo;
},
//选择某一项类目
chooseSub: function(e) {
let index = e.currentTarget.dataset.index;
this.setData({
activeIdx: index
})
this.getRect(index);
},
//获取类目的宽高
getRect: function (index) {
let that = this;
let query = wx.createSelectorQuery();
query.select("#v" + index).boundingClientRect(function (rect) {
that.data.scrollInfo.subLeft = rect.left; //元素一半宽度
that.data.scrollInfo.subHalfWidth = rect.width / 2;
that.moveTo();
}).exec()
},
//移动导航栏
moveTo: function() {
let subLeft = this.data.scrollInfo.subLeft;
let subHalfWidth = this.data.scrollInfo.subHalfWidth;
let prevDistance = this.data.scrollInfo.prevDistance;
let screenHalfwidth = this.data.scrollInfo.screenHalfwidth;
let needScroll = subLeft - screenHalfwidth + subHalfWidth;
let scrollLeft = needScroll + prevDistance;
this.setData({
scrollLeft: scrollLeft
})
},
//记录滚动的距离
scrollMove: function(e) {
let distance = e.detail.scrollLeft;
this.data.scrollInfo.prevDistance = distance
},复制代码
有两种特殊状况this
因此仍是正常运行.spa