获取滚动条宽度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
let scrollBarWidth;

export default function () {
if (scrollBarWidth !== undefined) return scrollBarWidth;
const outer = document.createElement('div');
outer.style.visibility = 'hidden';
outer.style.width = '100px';
outer.style.position = 'absolute';
outer.style.top = '-9999px';
document.body.appendChild(outer);

const widthNoScroll = outer.offsetWidth;
outer.style.overflow = 'scroll';

const inner = document.createElement('div');
inner.style.width = '100%';
outer.appendChild(inner);

const widthWithScroll = inner.offsetWidth;
outer.parentNode.removeChild(outer);
scrollBarWidth = (widthNoScroll - widthWithScroll) / (window.devicePixelRatio || 2);
return scrollBarWidth
}

实现弹窗背景固定方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let top = 0

export function lock(isFixed = true) {
let bodyEl = document.body
console.log(ScrollBarWidth())
if (isFixed) {
top = window.scrollY

bodyEl.style.position = 'fixed'
bodyEl.style.top = `-${top}px`
bodyEl.style.right = `${ScrollBarWidth()}px`
} else {
bodyEl.style.position = ''
bodyEl.style.right = ''
bodyEl.style.top = ''

window.scrollTo(0, top) // 回到原先的top
}
}