-
Notifications
You must be signed in to change notification settings - Fork 14
/
getScrollbarWidth.ts
51 lines (40 loc) · 1.16 KB
/
getScrollbarWidth.ts
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
import css from 'dom-css';
let scrollbarWidth: number | undefined = undefined;
let pxRatio: number = getPxRatio();
export default function getScrollbarWidth() {
/**
* Check zoom ratio. If it was changed, then it would update scrollbatWidth
*/
const newPxRatio = getPxRatio();
if (pxRatio !== newPxRatio) {
scrollbarWidth = getScrollbarWidthFromDom();
pxRatio = newPxRatio;
}
if (typeof scrollbarWidth === 'number') return scrollbarWidth;
/* istanbul ignore else */
if (typeof document !== 'undefined') {
scrollbarWidth = getScrollbarWidthFromDom();
} else {
scrollbarWidth = 0;
}
return scrollbarWidth || 0;
}
function getScrollbarWidthFromDom() {
const div = document.createElement('div');
css(div, {
width: 100,
height: 100,
position: 'absolute',
top: -9999,
overflow: 'scroll',
MsOverflowStyle: 'scrollbar',
});
document.body.appendChild(div);
const result = div.offsetWidth - div.clientWidth;
document.body.removeChild(div);
return result;
}
function getPxRatio() {
if (typeof window === 'undefined') return 1;
return window.screen.availWidth / document.documentElement.clientWidth;
}