-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.es6
53 lines (45 loc) · 1.69 KB
/
index.es6
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
function scrollWrapperElements(element, options) {
let elementRect = element.getBoundingClientRect();
let wrapper = element.parentNode;
while (wrapper != document.body) {
let wrapperRect = wrapper.getBoundingClientRect();
let margin = options.margin;
let deltaX = 0, deltaY = 0;
if (elementRect.top < wrapperRect.top + margin) {
deltaY = elementRect.top - wrapperRect.top - margin;
} else if (elementRect.bottom > wrapperRect.bottom - margin) {
deltaY = elementRect.bottom - wrapperRect.bottom + margin;
}
if (elementRect.left < wrapperRect.left + margin) {
deltaX = elementRect.left - wrapperRect.left - margin;
} else if (elementRect.right > wrapperRect.right - margin) {
deltaX = elementRect.right - wrapperRect.right + margin;
}
wrapper.scrollTop += deltaY;
wrapper.scrollLeft += deltaX;
wrapper = wrapper.parentNode;
}
return elementRect;
}
function scrollWindow(element, options, elementRect) {
let margin = options.margin;
let deltaX = 0, deltaY = 0;
if (elementRect.top < 0 + margin) {
deltaY = elementRect.top - margin;
} else if (elementRect.bottom > window.innerHeight - margin) {
deltaY = elementRect.bottom - window.innerHeight + margin;
}
if (elementRect.left < 0 + margin) {
deltaX = elementRect.left - margin;
} else if (elementRect.right > window.innerWidth - margin) {
deltaX = elementRect.right - window.innerWidth + margin;
}
window.scrollBy(deltaX, deltaY);
}
function scrollTo(element, options) {
options = options || {}
options.margin = options.margin || 0
var rect = scrollWrapperElements(element, options);
scrollWindow(element, options, rect);
}
export default scrollTo;