// Create the measurement node
var scrollp = document.createElement("p");
scrollp.style.overflow = 'scroll';
document.body.appendChild(scrollp);
// Get the scrollbar width
var scrollbarWidth = scrollp.offsetWidth - scrollp.clientWidth;
console.warn(scrollbarWidth); // Mac: 15
// Delete the p
document.body.removeChild(scrollp);
我记得也是17px
chrome的滚动条 我给关了 所以没测试
window.innerWidth浏览器可用宽度document.body.clientWidthbody的宽度我这个式子是在body没有
margin、padding、border的情况下得到的如果你要是有的话可以做减法
另外科普一下:
screen.width屏幕分辨率宽度document.body.scrollWidth页面完整宽度document.body.scrollHeight页面完整宽度document.body.offsetWidth网页课件区域宽度document.body.offsetHeight网页课件区域高度用兩層 p
外層先設定
overflow: scroll,量取內層 p 寬度再將外層 p 設定
overflow: hidden,再量內層 p 寬度兩個寬度差就是 scrollbar 的寬度
https://jsfiddle.net/fdamw8sb/
或是直接用
offsetWidth跟clientWidth的差值也能算出來ref: https://davidwalsh.name/detect-scrollbar-width
默认滚动条不记在body中
在20px左右
我记得是17px
得自己量量,有时候更新一次版本换一次
在body无
border-width的情况下window.innerWidth - document.body.clientWidth