1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | interface ScrollableElement {
|
24 | element: HTMLElement,
|
25 | scrollTop: number,
|
26 | scrollLeft: number
|
27 | }
|
28 |
|
29 | export function focusWithoutScrolling(element: HTMLElement) {
|
30 | if (supportsPreventScroll()) {
|
31 | element.focus({preventScroll: true});
|
32 | } else {
|
33 | let scrollableElements = getScrollableElements(element);
|
34 | element.focus();
|
35 | restoreScrollPosition(scrollableElements);
|
36 | }
|
37 | }
|
38 |
|
39 | let supportsPreventScrollCached: boolean = null;
|
40 | function supportsPreventScroll() {
|
41 | if (supportsPreventScrollCached == null) {
|
42 | supportsPreventScrollCached = false;
|
43 | try {
|
44 | var focusElem = document.createElement('div');
|
45 | focusElem.focus({
|
46 | get preventScroll() {
|
47 | supportsPreventScrollCached = true;
|
48 | return true;
|
49 | }
|
50 | });
|
51 | } catch (e) {
|
52 |
|
53 | }
|
54 | }
|
55 |
|
56 | return supportsPreventScrollCached;
|
57 | }
|
58 |
|
59 | function getScrollableElements(element: HTMLElement): ScrollableElement[] {
|
60 | var parent = element.parentNode;
|
61 | var scrollableElements: ScrollableElement[] = [];
|
62 | var rootScrollingElement = document.scrollingElement || document.documentElement;
|
63 |
|
64 | while (parent instanceof HTMLElement && parent !== rootScrollingElement) {
|
65 | if (
|
66 | parent.offsetHeight < parent.scrollHeight ||
|
67 | parent.offsetWidth < parent.scrollWidth
|
68 | ) {
|
69 | scrollableElements.push({
|
70 | element: parent,
|
71 | scrollTop: parent.scrollTop,
|
72 | scrollLeft: parent.scrollLeft
|
73 | });
|
74 | }
|
75 | parent = parent.parentNode;
|
76 | }
|
77 |
|
78 | if (rootScrollingElement instanceof HTMLElement) {
|
79 | scrollableElements.push({
|
80 | element: rootScrollingElement,
|
81 | scrollTop: rootScrollingElement.scrollTop,
|
82 | scrollLeft: rootScrollingElement.scrollLeft
|
83 | });
|
84 | }
|
85 |
|
86 | return scrollableElements;
|
87 | }
|
88 |
|
89 | function restoreScrollPosition(scrollableElements: ScrollableElement[]) {
|
90 | for (let {element, scrollTop, scrollLeft} of scrollableElements) {
|
91 | element.scrollTop = scrollTop;
|
92 | element.scrollLeft = scrollLeft;
|
93 | }
|
94 | }
|