-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
111 lines (92 loc) · 2.42 KB
/
index.js
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
'use strict'
function BScroll(ctx) {
var el = ctx.firstElementChild || ctx.firstChild
var OFFSET = 50
var vy = 0
var F = 150
var isDown = false
var isTransform = false
var cur = 0
var target = 0
var requestId
ctx.addEventListener('touchstart', function (e) {
if (isTransform) return
window.cancelAnimationFrame(requestId)
vy = 0
this._oy = e.changedTouches[0].clientY - cur
this._cy = e.changedTouches[0].clientY
this._oh = this.scrollHeight
this._ch = this.clientHeight
this._startTime = e.timeStamp
isDown = true
})
ctx.addEventListener('touchmove', function (e) {
if (isDown) {
if (e.timeStamp - this._startTime > 50) {
this._startTime = e.timeStamp
cur = e.changedTouches[0].clientY - this._oy
if (cur > 0) {
cur *= F / (F + cur)
} else if (cur < this._ch - this._oh) {
cur += this._oh - this._ch
cur = (cur * F) / (F - cur) - this._oh + this._ch
}
transform(cur)
}
vy = e.changedTouches[0].clientY - this._cy
this._cy = e.changedTouches[0].clientY
}
}, false)
ctx.addEventListener('touchend', function () {
if (isDown) {
isDown = false
var friction = ((vy >> 31) * 2 + 1) * 0.5
var oh = this.scrollHeight - this.clientHeight
var bounce = function () {
vy -= friction
cur += vy
requestId = window.requestAnimationFrame(bounce)
transform(cur)
if (-cur - oh > OFFSET) {
target = -oh
window.cancelAnimationFrame(requestId)
ease()
return
}
if (cur > OFFSET) {
window.cancelAnimationFrame(requestId)
ease()
return
}
if (Math.abs(vy) < 1) {
window.cancelAnimationFrame(requestId)
if (cur > 0) {
ease()
return
}
if (-cur > oh) {
target = -oh
ease()
return
}
}
}
bounce()
}
})
function ease() {
isTransform = true
cur -= (cur - target) * 0.2
var requestId = window.requestAnimationFrame(ease)
if (Math.abs(cur - target) < 1) {
cur = target
window.cancelAnimationFrame(requestId)
isTransform = false
}
transform(cur)
}
function transform(y) {
el.style.transform = 'translateY(' + y + 'px) translateZ(0)'
}
}
module.exports = BScroll