// 方法函数
getRect (ele) { // 获取点击元素的信息,ele为传入的id
var that = this
wx.createSelectorQuery().select(ele).boundingClientRect(function (rect) {
let moveParams = that.data.moveParams
moveParams.subLeft = rect.left
moveParams.subHalfWidth = rect.width / 2
that.moveTo()
}).exec()
},
handleCheckOutChoose (e) {
let ele = e.currentTarget.id
this.setData({
chooseId: e.currentTarget.dataset.index
})
this.getRect('#' + ele)
},
scrollMove (e) {
let moveParams = this.data.moveParams
moveParams.scrollLeft = e.detail.scrollLeft
this.setData({
moveParams: moveParams
})
},
moveTo () {
let subLeft = this.data.moveParams.subLeft
let screenHalfWidth = this.data.moveParams.screenHalfWidth
let subHalfWidth = this.data.moveParams.subHalfWidth
let scrollLeft = this.data.moveParams.scrollLeft
let distance = subLeft - screenHalfWidth + subHalfWidth
scrollLeft = scrollLeft + distance
this.setData({
scrollLeft: scrollLeft
})
},
//data数据
scrollLeft: 0,//移动的距离
// 大多数计算用到的参数,都在moveParams对象中
moveParams: {
activeIdx: null,
scrollLeft: 0, // scroll-view滚动的距离,默认为0,因为没有触发滚动
subLeft: 0, // 点击元素距离屏幕左边的距离
subHalfWidth: 0, // 点击元素的宽度一半
screenHalfWidth: wx.getSystemInfoSync().windowWidth / 2// 屏幕宽度的一半
},
tabList: [{
name: '服饰配饰',
title: '精选优惠',
id: 1
}, {
name: '美妆个护',
title: '精选优惠',
id: 2
}, {
name: '家居百货',
title: '精选优惠',
id: 3
}, {
name: '母婴儿童',
title: '精选优惠',
id: 4
}, {
name: '服饰配饰',
title: '精选优惠',
id: 5
}, {
name: '美妆个护',
title: '精选优惠',
id: 6
}, {
name: '家居百货',
title: '精选优惠',
id: 7
}, {
name: '母婴儿童',
title: '精选优惠',
id: 8
}
],
chooseId: 1,
//wxml代码
<scroll-view bindscroll="scrollMove" scroll-left="{{scrollLeft}}" id="fixed" scroll-with-animation style="top:{{headerHeight}}px;" scroll-x class="index-inner-backListShop-scroll {{menuFixedCategory?'fiexdScroll':''}} paddingSide ">
<view class="index-inner-backListShop-scroll-tab">
<view id="ele{{index}}" catchtap="handleCheckOutChoose" data-index="{{i.id}}" wx:for="{{tabList}}" wx:for-item="i" wx:key="i.id" class="index-inner-backListShop-scroll-tab-item">
<view class="name {{chooseId==i.id &&'chooseName'}} {{(menuFixedCategory && chooseId==i.id)?'xiahuaxian':''}}">
{{i.name}}
</view>
<view wx:if="{{!menuFixedCategory}}" class=" title {{chooseId==i.id &&'chooseTitle'}}">
{{i.title}}
</view>
</view>
</view>
</scroll-view>