在項目中遇到點擊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