Created
November 9, 2021 10:40
-
-
Save liuwenzhuang/14d22bf11957a79ac4ce7434c2b0eb7c to your computer and use it in GitHub Desktop.
calc scrollbar size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const placeHolderElemAttr = { | |
position: 'absolute', | |
top: '-99999px', | |
left: '-99999px', | |
width: '100px', | |
height: '100px', | |
overflow: 'scroll' | |
}; | |
interface CalcScrollbarSize { | |
(direction: 'vertical' | 'horizontal'): number; | |
verticalWidth: number; | |
horizontalHeight: number; | |
} | |
/** | |
* 计算滚动条高度/宽度 | |
*/ | |
export const calcScrollbarSize = <CalcScrollbarSize>function (direction = 'vertical') { | |
// has been calcated => return | |
if (calcScrollbarSize.verticalWidth && direction === 'vertical') { | |
return calcScrollbarSize.verticalWidth; | |
} | |
if (calcScrollbarSize.horizontalHeight && direction === 'horizontal') { | |
return calcScrollbarSize.horizontalHeight; | |
} | |
const placeHolderElem = document.createElement('div'); | |
Object.keys(placeHolderElemAttr).forEach(key => { | |
placeHolderElem.style[key] = placeHolderElemAttr[key]; | |
}); | |
document.body.appendChild(placeHolderElem); | |
let size: number; | |
if (direction === 'horizontal') { | |
calcScrollbarSize.horizontalHeight = size = placeHolderElem.offsetHeight - placeHolderElem.clientHeight; | |
} | |
if (direction === 'vertical') { | |
calcScrollbarSize.verticalWidth = size = placeHolderElem.offsetWidth - placeHolderElem.clientWidth; | |
} | |
document.body.removeChild(placeHolderElem); | |
return size; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment