知识点:offsetWidth:获取到的值是width+padding+border;
clientWidth: 获取对象可见内容的宽度,不包括滚动条,不包括边框;
function getScrollbarWidth() {
var odiv = document.createElement('div'),//创建一个div
styles = {
width: '100px',
height: '100px',
overflowY: 'scroll'//让他有滚动条
}, i, scrollbarWidth;
for (i in styles) odiv.style[i] = styles[i];
document.body.appendChild(odiv);//把div添加到body中
scrollbarWidth = odiv.offsetWidth - odiv.clientWidth;//相减
odiv.remove();//移除创建的div
return scrollbarWidth;//返回滚动条宽度
}
方法使用
console.dir(getScrollbarWidth());