// components/TopTabbar/index.js Component({ /** * 组件的属性列表 */ properties: { tabList: { type: Array, value: [] }, border: { type: Boolean, value: true }, tabIndex: { type: Number, value: 0 }, }, observers: { tabIndex: function (n) { this.click(n); }, }, /** * 组件的初始数据 */ data: { tabDataIndex: 0, scroll_width: 0, scroll_left: 0 }, lifetimes: { attached: function () {}, detached: function () {}, }, pageLifetimes: { // 组件所在页面的生命周期函数 show: function () { this.onLoad(); }, hide: function () {}, resize: function () {}, }, /** * 组件的方法列表 */ methods: { onLoad() { var that = this; that.createSelectorQuery().select('#topTabbar-item').boundingClientRect(function (res) { try { that.setData({ scroll_width: res.width }) } catch (e) {} }).exec(); }, changeType(e) { var that = this; if (this.data.tabDataIndex == e.currentTarget.dataset.index) return; let index = e.currentTarget.dataset.index; let item = e.currentTarget.dataset.item; let offsetLeft = e.currentTarget.offsetLeft; let scroll_left = this.data.scroll_left; that.createSelectorQuery().select('#topTabbar_select_' + index).boundingClientRect(function (res) { // //console.log(res) scroll_left = offsetLeft - that.data.scroll_width / 2 + (res.width / 2); that.setData({ tabDataIndex: index, scroll_left: scroll_left }); that.triggerEvent('change', { index, item }) }).exec(); }, click(eindex) { var that = this; if (this.data.tabDataIndex == eindex) return; let index = eindex; let item = this.data.tabList[eindex]; let scroll_left = this.data.scroll_left; that.createSelectorQuery().select('#topTabbar_select_' + index).boundingClientRect(function (res) { scroll_left = res.left - that.data.scroll_width / 2 + (res.width / 2); that.setData({ tabDataIndex: index, scroll_left: scroll_left }); that.triggerEvent('change', { index, item }) }).exec(); } } })