-
Notifications
You must be signed in to change notification settings - Fork 11
/
vue-bounce.js
104 lines (73 loc) · 3.01 KB
/
vue-bounce.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
/**
* @author ziPeiJun <[email protected]>
* @license MIT
*/
class vueBounce {
constructor () {
this._startPoint = null
this._handleStart = null
this._handleMove = null
this._handleEnd = null
}
install (Vue, { name } = {}) {
const directiveName = name || 'bounce'
const directive = (el, binding) => {
if (this._handleStart === null || this._handleMove === null || this._handleEnd === null) {
this._handleStart = this._touchstartEvent.bind(this, this)
this._handleMove = this._touchmoveEvent.bind(this, this, el)
this._handleEnd = this._touchendEvent.bind(this, this)
}
if (binding.value) { // 缺省和 false 禁用 bounce 效果、true 启用
el.removeEventListener('touchstart', this._handleStart)
window.removeEventListener('touchmove', this._handleMove)
window.removeEventListener('touchend', this._handleEnd)
return void 0
}
el.addEventListener('touchstart', this._handleStart)
window.addEventListener('touchmove', this._handleMove, {
passive: false
})
window.addEventListener('touchend', this._handleEnd)
}
Vue.directive(directiveName, directive.bind(this))
}
_getScrollTop (el) { // 获取滚动高度
return el.scrollTop
}
_getScrollHeight (el) { // 滚动内容的高度
return el.scrollHeight
}
_getClientHeight (el) { // 滚动容器的高度
return el.clientHeight
}
_getPoint (e) { // 获取手指位置
return {
x: e.touches ? e.touches[0].pageX : e.clientX,
y: e.touches ? e.touches[0].pageY : e.clientY
}
}
_preventDefault (e) { // 在可以阻止的时候阻止滚动行为
if (e.cancelable) e.preventDefault()
}
_touchstartEvent (context, e) {
context._startPoint = context._getPoint(e)
}
_touchmoveEvent (context, el, e) {
if (!context._startPoint) return void 0
const curPoint = context._getPoint(e) // 当前点
const moveY = curPoint.y - context._startPoint.y // 和起点比,移动的距离,大于0向下拉,小于0向上拉
const scrollTop = context._getScrollTop(el) // 当前滚动条的距离
if (moveY > 0 && scrollTop <= 0) { // 如果在顶部,则阻止浏览器默认事件
context._preventDefault(e)
return void 0
}
const scrollHeight = context._getScrollHeight(el) // 滚动内容的高度
const clientHeight = context._getClientHeight(el) // 滚动容器的高度
const toBottom = scrollHeight - clientHeight - scrollTop // 滚动条距离底部的距离
if (moveY < 0 && toBottom <= 0) context._preventDefault(e) // 如果在底部,则阻止浏览器默认事件
}
_touchendEvent (context, e) {
context._startPoint = null
}
}
export default new vueBounce