index.js
2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// components/scroll-number/index.js
Component({
externalClasses: ['container-class', 'item-class', 'dot-class'],
properties: {
value: {
type: String,
value: ''
},
/** 一次滚动耗时 单位ms */
duration: {
type: Number,
value: 1600
},
/** 每个数字之间的延迟滚动 */
delay: {
type: Number,
value: 200
}
},
data: {
valArr: [],
aniArr: [], // 动画列表,和valArr对应
numArr: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], // 所有数字
itemHeight: 0 // 数字项的高度
},
observers: {
value: function (newVal) {
// 监听value变化,格式化为valArr
setTimeout(() => {
let valArr = []
if (newVal) {
valArr = newVal.split('').map(o => {
return {
val: o,
isNaN: isNaN(o)
}
})
}
this.setData({
valArr: valArr
})
this.getNumberHeight()
}, 0);
}
},
methods: {
/** 计算数字高度 */
getNumberHeight() {
if (this.data.itemHeight > 0) {
this.startScrollAni()
return
}
const query = this.createSelectorQuery()
query.select('.number-item').boundingClientRect()
query.exec((res) => {
// 页面里没有数字项(.number-item)时 res[0] 为 null,做保护避免报错
if (res && res[0] && res[0].height) {
this.setData({
itemHeight: res[0].height
})
this.startScrollAni()
} else {
// 重置状态,等待下一次 value 变化时再计算高度
this.setData({
itemHeight: 0,
aniArr: []
})
}
})
},
/** 开始滚动动画 */
startScrollAni() {
if (this.data.itemHeight <= 0) return
const aniArr = []
this.data.valArr.forEach((item, index) => {
if (!item.isNaN) {
aniArr.push(`transition-delay: ${this.data.delay * index}ms; top: ${-this.data.itemHeight * (this.data.numArr[parseInt(item.val)] + 10)}px;`)
} else {
aniArr.push(null)
}
})
this.setData({
aniArr: aniArr
})
}
}
})