This is relatively simple, just a record.
Create a nested node, let the outer node generate a scroll bar, and then use offsetWidth - clientWidth to get the scroll bar width. It should be noted that in order to avoid page shaking, you can set the outer element position:absolute and visibility:hidden
Reference:
function getScrollWith(){
var wrap = setAttributes(document.createElement('div'),{
style : {
width : '200px',
height: '200px',
overflow: 'auto',
position:'absolute',
visibility:'hidden'
}
})
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;
}