feat(tab): tab组件支持选中项自动滑动到中间位置 @rex-zsd (#347)

#307
This commit is contained in:
rex 2018-07-09 21:34:27 +08:00 committed by Yao
parent ab7d27c53a
commit 45994120a9
2 changed files with 24 additions and 1 deletions

View File

@ -24,10 +24,29 @@ Component({
}
},
data: {
scrollLeft: 0
},
methods: {
_handleScroll(selectedId) {
const query = wx.createSelectorQuery().in(this);
query.select(`#item-${selectedId}`).boundingClientRect();
query.select('#scroll-view').boundingClientRect();
query.select('#scroll-view').scrollOffset();
query.exec(res => {
this.setData({
scrollLeft: res[2].scrollLeft + res[0].left + res[0].width / 2 - res[1].width / 2
});
});
},
_handleZanTabChange(e) {
const selectedId = e.currentTarget.dataset.itemId;
if (this.data.scroll) {
this._handleScroll(selectedId);
}
this.setData({
selectedId
});

View File

@ -4,8 +4,11 @@
>
<block wx:if="{{ scroll }}">
<scroll-view
id="scroll-view"
class="zan-tab__bd zan-tab__bd--scroll {{ fixed ? 'zan-tab__bd--fixed' : '' }}"
scroll-x="true"
scroll-x
scroll-with-animation
scroll-left="{{ scrollLeft }}"
style="height: {{ height ? height + 'px' : 'auto' }}"
>
<template
@ -34,6 +37,7 @@
wx:for="{{ list }}"
wx:key="id"
class="zan-tab__item {{ selectedId == item.id ? 'zan-tab__item--selected' : '' }}"
id="item-{{ item.id }}"
data-item-id="{{ item.id }}"
bindtap="_handleZanTabChange"
>