This is a simple record.
Create a nested node, let the outer node generate a scroll bar, and then use offsetWidth-clientWidth to obtain the scroll bar width. To avoid page jitter, you can set the outer element position: absolute and visibility: hidden.
Refer:
Copy codeThe Code is as follows:
Function getScrollWith (){
Var wrap = setAttributes (document. createElement ('div '),{
Style :{
Width: '200px ',
Height: '200px ',
Overflow: 'auto ',
Position: 'absolute ',
Visibility: 'ddy'
}
})
Var inner = setAttributes (document. createElement ('div '),{
Style :{
Width: '100px ',
Height: '2000px'
}
})
Document. body. appendChild (wrap );
Wrap. appendChild (inner );
Var w = wrap. offsetWidth-wrap. clientWidth;
Document. body. removeChild (wrap );
Wrap = null;
Inner = null;
Return w;
}
Function setAttributes (elem, opts ){
For (var key in opts ){
If (typeof opts [key] = 'string '){
Elem [key] = opts [key];
} Else {
If (! Elem [key]) {
Elem [key] = {};
}
SetAttributes (elem [key], opts [key]);
}
}
Return elem;
}