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;
}
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn