1 |
|
2 | function getOffset(element, parent) {
|
3 | return {
|
4 | top: Math.round(element.getBoundingClientRect().top - parent.getBoundingClientRect().top),
|
5 | left: Math.round(element.getBoundingClientRect().left - parent.getBoundingClientRect().left)
|
6 | };
|
7 | }
|
8 |
|
9 |
|
10 | var locks = new Set();
|
11 | function lockBodyScrolling(lockingEl) {
|
12 | locks.add(lockingEl);
|
13 | document.body.classList.add("sl-scroll-lock");
|
14 | }
|
15 | function unlockBodyScrolling(lockingEl) {
|
16 | locks.delete(lockingEl);
|
17 | if (locks.size === 0) {
|
18 | document.body.classList.remove("sl-scroll-lock");
|
19 | }
|
20 | }
|
21 | function scrollIntoView(element, container, direction = "vertical", behavior = "smooth") {
|
22 | const offset = getOffset(element, container);
|
23 | const offsetTop = offset.top + container.scrollTop;
|
24 | const offsetLeft = offset.left + container.scrollLeft;
|
25 | const minX = container.scrollLeft;
|
26 | const maxX = container.scrollLeft + container.offsetWidth;
|
27 | const minY = container.scrollTop;
|
28 | const maxY = container.scrollTop + container.offsetHeight;
|
29 | if (direction === "horizontal" || direction === "both") {
|
30 | if (offsetLeft < minX) {
|
31 | container.scrollTo({ left: offsetLeft, behavior });
|
32 | } else if (offsetLeft + element.clientWidth > maxX) {
|
33 | container.scrollTo({ left: offsetLeft - container.offsetWidth + element.clientWidth, behavior });
|
34 | }
|
35 | }
|
36 | if (direction === "vertical" || direction === "both") {
|
37 | if (offsetTop < minY) {
|
38 | container.scrollTo({ top: offsetTop, behavior });
|
39 | } else if (offsetTop + element.clientHeight > maxY) {
|
40 | container.scrollTo({ top: offsetTop - container.offsetHeight + element.clientHeight, behavior });
|
41 | }
|
42 | }
|
43 | }
|
44 |
|
45 | export {
|
46 | lockBodyScrolling,
|
47 | unlockBodyScrolling,
|
48 | scrollIntoView
|
49 | };
|