此功能应为您提供滚动条的宽度
function getScrollbarWidth() { // Creating invisible container const outer = document.createElement('div'); outer.style.visibility = 'hidden'; outer.style.overflow = 'scroll'; // forcing scrollbar to appear outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps document.body.appendChild(outer); // Creating inner element and placing it in the container const inner = document.createElement('div'); outer.appendChild(inner); // Calculating difference between container's full width and the child width const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth); // Removing temporary elements from the DOM outer.parentNode.removeChild(outer); return scrollbarWidth;}基本步骤如下:
- 创建隐藏的div(外部)并获取其偏移宽度
- 使用CSS溢出属性强制滚动条显示在div(外部)中
- 创建新的div(内部)并附加到外部,将其宽度设置为“ 100%”并获得偏移宽度
- 根据收集的偏移量计算滚动条宽度
更新资料
如果在Windows(metro)应用程序上使用此功能,请确保将“外部” div 的-ms-overflow-
style属性设置为
scrollbar,否则将无法正确检测到宽度。(代码已更新)
更新#2 在默认设置为“仅在滚动时显示滚动条”(Yosemite及更高版本)的Mac OS上,这将不起作用。



