这个比较简单,做个记录而已。

创建一个嵌套节点,让外层节点产生滚动条,然后用offsetWidth - clientWidth即可获得滚动条宽度。需要注意的是为了避免页面抖动,可以设置外层元素position:absolute和visibility:hidden

参考:

    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;
}



相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-22
  • 2021-09-05
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-03
  • 2022-12-23
  • 2021-06-06
  • 2021-11-08
  • 2022-12-23
相关资源
相似解决方案