-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
64 lines (61 loc) · 1.96 KB
/
index.js
File metadata and controls
64 lines (61 loc) · 1.96 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
let Vue;
const install = (_Vue, options = {}) => {
Vue = _Vue;
Vue.directive('back', {
inserted (el, bindings) {
const scrollPosition = calculation(bindings.value)
const { el: selector, duration = 300, distance = 0, interval = 10 } = options;
let eventTarget = window;
let scrollContainer = document.documentElement;
if (selector) {
let wrapper = document.querySelector(selector);
if (wrapper) {
eventTarget = wrapper;
scrollContainer = wrapper;
}
}
const appearancePosition = calculation(distance)
const handleScroll = () => {
el.style.display = scrollContainer.scrollTop >= appearancePosition ? 'block' : 'none';
}
handleScroll();
eventTarget.addEventListener('scroll', handleScroll);
el.addEventListener('click', function () {
if (this.isScroll) return;
this.isScroll = true;
eventTarget.removeEventListener('scroll', handleScroll);
const distance = scrollContainer.scrollTop;
const step = (distance / duration) * interval;
const timer = setInterval(() => {
let curTop = scrollContainer.scrollTop
curTop -= step;
if (curTop <= scrollPosition) {
clearInterval(timer);
scrollContainer.scrollTop = scrollPosition;
handleScroll();
eventTarget.addEventListener('scroll', handleScroll);
this.isScroll = false;
return;
}
scrollContainer.scrollTop = curTop;
}, interval)
})
}
})
}
function calculation (num = 0) {
let reg = /^(\d+)(px|page)?$/;
let res = 0;
if (reg.test(num)) {
let [, count, unit = 'px'] = reg.exec(num);
if (unit === 'px') {
res = count;
} else if (unit === 'page') {
res = count * document.documentElement.clientHeight
}
}
return res
}
export default {
install
}