Skip to content

Commit 6c444bd

Browse files
committed
fix: scrollbar width detect
1 parent 4c85e2d commit 6c444bd

1 file changed

Lines changed: 10 additions & 14 deletions

File tree

source/js/components/scrollbar-width.js

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
* --------------------------------------------------------------------------
55
*/
66
import AbstractComponent from '~/components/abstract';
7+
import ScrollBarHelper from 'bootstrap/js/src/util/scrollbar';
78

89
/**
910
* Calc scrollbar width.
@@ -24,26 +25,24 @@ class ScrollbarWidth extends AbstractComponent {
2425
* Init events.
2526
*/
2627
init() {
27-
this.scrollbarOuter = document.createElement('div');
28-
this.scrollbarOuter.className = 'scrollbar-width';
29-
this.scrollbarOuter.style = 'z-index: -9999; position: absolute; visibility: hidden; width: 100px; margin-left: -100px; overflow: scroll;';
30-
document.documentElement.appendChild(this.scrollbarOuter);
31-
this.scrollbarInner = document.createElement('div');
32-
this.scrollbarInner.style = 'width: 100%;';
33-
this.scrollbarOuter.appendChild(this.scrollbarInner);
28+
this.helper = new ScrollBarHelper();
3429

3530
window.addEventListener('resize', this.onResize);
3631

32+
this.observer = new ResizeObserver(this.onResize);
33+
this.observer.observe(document.documentElement);
34+
3735
this.updateWidth();
3836
}
3937

4038
/**
4139
* Remove events.
4240
*/
4341
destroy() {
44-
window.removeEventListener('resize', this.onResize);
42+
this.observer?.disconnect();
43+
this.observer = null;
4544

46-
this.scrollbarOuter.remove();
45+
window.removeEventListener('resize', this.onResize);
4746
}
4847

4948
/**
@@ -57,11 +56,8 @@ class ScrollbarWidth extends AbstractComponent {
5756
* Update width.
5857
*/
5958
updateWidth() {
60-
this.width = 100 - this.scrollbarInner.offsetWidth;
61-
if (this.widthLast !== this.width) {
62-
document.documentElement.style.setProperty('--scrollbar-width', `${this.width}px`);
63-
this.widthLast = this.width;
64-
}
59+
this.width = this.helper.getWidth();
60+
document.documentElement.style.setProperty('--scrollbar-width', `${this.width}px`);
6561
}
6662
}
6763

0 commit comments

Comments
 (0)