1 | import Vue from 'vue';
|
2 |
|
3 | export default function scrollIntoView(container, selected) {
|
4 | if (Vue.prototype.$isServer) return;
|
5 |
|
6 | if (!selected) {
|
7 | container.scrollTop = 0;
|
8 | return;
|
9 | }
|
10 |
|
11 | const offsetParents = [];
|
12 | let pointer = selected.offsetParent;
|
13 | while (pointer && container !== pointer && container.contains(pointer)) {
|
14 | offsetParents.push(pointer);
|
15 | pointer = pointer.offsetParent;
|
16 | }
|
17 | const top = selected.offsetTop + offsetParents.reduce((prev, curr) => (prev + curr.offsetTop), 0);
|
18 | const bottom = top + selected.offsetHeight;
|
19 | const viewRectTop = container.scrollTop;
|
20 | const viewRectBottom = viewRectTop + container.clientHeight;
|
21 |
|
22 | if (top < viewRectTop) {
|
23 | container.scrollTop = top;
|
24 | } else if (bottom > viewRectBottom) {
|
25 | container.scrollTop = bottom - container.clientHeight;
|
26 | }
|
27 | }
|