1.创建一个嵌套节点,让外层节点产生滚动条。
2.用offsetWidth - clientWidth 即可获得滚动条宽度。
为了避免页面抖动,可以设置外层元素position:absolute和visibility:hidden
代码如下:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>滚动条宽度</title> 6 <script type="text/javascript"> 7 window.onload = function(){ 8 function getScrollWith(){ 9 var wrap = setAttributes(document.createElement('div'),{ 10 style : { 11 width : '200px', 12 height: '200px', 13 overflow: 'auto', 14 position:'absolute', 15 visibility:'hidden' 16 } 17 }); 18 19 var inner = setAttributes(document.createElement('div'),{ 20 style : { 21 width : '100px', 22 height: '2000px' 23 } 24 }); 25 26 document.body.appendChild(wrap); 27 wrap.appendChild(inner); 28 var w = wrap.offsetWidth - wrap.clientWidth; 29 document.body.removeChild(wrap); 30 wrap = null; 31 inner = null; 32 return w; 33 } 34 //设置CSS样式 35 function setAttributes(elem,opts){ 36 for(var key in opts){ 37 if(typeof opts[key] == 'string'){ 38 elem[key] = opts[key]; 39 }else{ 40 if(!elem[key]){ 41 elem[key] = {}; 42 } 43 setAttributes(elem[key],opts[key]); 44 } 45 } 46 return elem; 47 } 48 var a = getScrollWith(); 49 alert(a); 50 } 51 </script> 52 </head> 53 54 <body> 55 </body> 56 </html>