// components/My_switch/index.js Component({ /** * 组件的属性列表 */ properties: { list: { type: Array, value: ['最新', '最热'] }, change: { type: Function } }, lifetimes: { ready: function () { const that = this; let query = wx.createSelectorQuery().in(this) query.select('.switch-box').boundingClientRect(); query.exec(function (res) { that.setData({ baseLeft: res[0].left }) that.chengeSelect() }) } }, /** * 组件的初始数据 */ data: { checkedItem: 0, //选中项 animationData: {}, //横线平移动画 baseLeft: 0, }, /** * 组件的方法列表 */ methods: { changeSwitch(e) { this.setData({ checkedItem: this.data.checkedItem == 0 ? 1 : 0 }) this.triggerEvent('change', this.data.list[this.data.checkedItem]) this.chengeSelect() }, chengeSelect() { let animation = wx.createAnimation({ duration: 1000, timingFunction: 'ease', }) let that = this; let query = wx.createSelectorQuery().in(this) query.select('.active').boundingClientRect(); query.exec(function (res) { animation.translate(res[0].left - that.data.baseLeft + 2).step({ duration: 300 }) that.setData({ animationData: animation.export() }) }) } } })