Skip to content

Commit

Permalink
style(getScrollbarWidth ): 根据不同的容器dom进行获取scroll 的宽度 (#1968)
Browse files Browse the repository at this point in the history
* fix(utils): `getScrollbarWidth` gets the error in the accuracy of scroll width

* chore: 根据不同的容器dom进行获取scroll 的宽度
  • Loading branch information
RSS1102 authored Oct 14, 2024
1 parent c765cde commit fdf8357
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions js/utils/getScrollbarWidth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,14 @@ export function getScrollbarWidthWithCSS() {
return scrollbarWidth;
}

// 获取 body 下滚动条宽度
export function getScrollbarWidth() {
const scrollDiv = document.createElement('div');
scrollDiv.style.cssText = 'width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;';
document.body.appendChild(scrollDiv);
const scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return scrollbarWidth;
/**
* @description: Calculate scroll bar width
* @param container Container used to calculate scrollbar width
* @default container: document.body
*/
export function getScrollbarWidth(container: HTMLElement = document.body) {
if (container === document.body) {
return window.innerWidth - document.documentElement.clientWidth;
}
return container.offsetWidth - container.clientWidth;
}

0 comments on commit fdf8357

Please sign in to comment.