使用JavaScript获取滚动条宽度 [英] Getting scroll bar width using JavaScript
问题描述
以下HTML将在div.container的右边缘显示滚动条。
The following HTML will display a scroll bar on the right inside edge of div.container.
是否可以确定滚动条的宽度?
Is it possible to determine the width of that scroll bar?
<div class="container" style="overflow-y:auto; height:40px;">
<div class="somethingBig"></div>
</div>
推荐答案
此函数应该为您提供滚动条的宽度
This function should give you width of scrollbar
function getScrollbarWidth() {
var outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.width = "100px";
outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps
document.body.appendChild(outer);
var widthNoScroll = outer.offsetWidth;
// force scrollbars
outer.style.overflow = "scroll";
// add innerdiv
var inner = document.createElement("div");
inner.style.width = "100%";
outer.appendChild(inner);
var widthWithScroll = inner.offsetWidth;
// remove divs
outer.parentNode.removeChild(outer);
return widthNoScroll - widthWithScroll;
}
这里的基本步骤是:
- 创建宽度设置为100px的隐藏div(外部)并获得偏移宽度(应为100)
- 强制滚动条显示在div(外部)使用CSS溢出属性
- 创建新的div(内部)并追加到外部,将其宽度设置为'100%'并获得偏移宽度
- 根据收集的偏移量计算滚动条宽度
- Create hidden div (outer) with width set to '100px' and get offset width (should be 100)
- Force scroll bars to appear in div (outer) using CSS overflow property
- Create new div (inner) and append to outer, set its width to '100%' and get offset width
- Calculate scrollbar width based on gathered offsets
此处的工作示例: http://jsfiddle.net/UU9kg/17/
更新
如果您在Windows(metro)应用程序上使用此功能,请确保设置 - ms-overflow-style 属性为滚动条
,否则将无法正确检测宽度。 (已更新代码)
If you're using this on a Windows (metro) App, make sure you set the -ms-overflow-style property of the 'outer' div to scrollbar
, otherwise the width will not be correctly detected. (code updated)
更新#2
这在Mac OS上无效,默认情况下滚动时只显示滚动条设置(Yosemite和up)。
Update #2 This will not work on Mac OS with the default "Only show scrollbars when scrolling" setting (Yosemite and up).
这篇关于使用JavaScript获取滚动条宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!