使用JavaScript获取滚动条宽度

use*_*531 105 javascript

以下HTML将在div.container的右侧内侧边缘显示滚动条.

是否可以确定滚动条的宽度?

<div class="container" style="overflow-y:auto; height:40px;">
  <div class="somethingBig"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

los*_*rce 216

这个函数应该给你滚动条的宽度

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;

}
Run Code Online (Sandbox Code Playgroud)

这里的基本步骤是:

  1. 创建宽度设置为'100px'的隐藏div(外部)并获得偏移宽度(应为100)
  2. 使用CSS overflow属性强制滚动条出现在div(外部)中
  3. 创建新div(内部)并追加到外部,将其宽度设置为"100%"并获得偏移宽度
  4. 根据收集的偏移量计算滚动条宽度

这里的工作示例:http://jsfiddle.net/UU9kg/17/

更新

如果您在Windows(metro)应用程序上使用它,请确保将"外部"div 的-ms-overflow-style属性设置为scrollbar,否则将无法正确检测宽度.(代码更新)

更新#2 这在Mac OS上无效,默认情况下"滚动时只显示滚动条"设置(Yosemite和up).


Vas*_*nyk 25

// offsetWidth包括滚动条的宽度,而clientWidth则不包含.按规则,它等于14-18px.所以:

 var scrollBarWidth = element.offsetWidth - element.clientWidth;
Run Code Online (Sandbox Code Playgroud)

  • offsetWidth不包括滚动条,至少在当前最新的chrome中 (2认同)
  • 我在 Windows 10 上的 Chrome 64 和 FireFox 58 上测试了这个解决方案,并且在我看来这是迄今为止最干净的解决方案。我想@DavidGuan 必须在 Mac OS X 上运行?在这种情况下,滚动条是一个叠加层,实际上并不影响 DOM 的几何形状,因此我希望 offsetWidth 和 clientWidth 在 Mac 上始终相等,除非您使用的是非 Mac 鼠标。 (2认同)
  • document.body.offsetWidth 不包括滚动条,但 myElement.offsetWidth 不包括滚动条,只要它不是正文。 (2认同)

pim*_*vdb 12

如果孩子占用容器的整个宽度(不包括滚动条)(默认值),则可以减去宽度:

var child = document.querySelector(".somethingBig");
var scrollbarWidth = child.parentNode.offsetWidth - child.offsetWidth;
Run Code Online (Sandbox Code Playgroud)


Ujj*_*pta 11

我认为这将简单快速 -

var scrollWidth= window.innerWidth-$(document).width()
Run Code Online (Sandbox Code Playgroud)

  • 我正在使用这个,不知道为什么你需要插入一个 DIV `const scrollbarWidth = window.innerWidth - document.body.offsetWidth` (6认同)
  • @Scott Leonard 如果你在 html 和 body 上有 `overflow:hidden` ,这不起作用。插入`&lt;div&gt;`是为了确保有一个带有滚动条的元素。 (3认同)

小智 8

如果你使用 jquery。ui,试试这个代码:

$.position.scrollbarWidth()
Run Code Online (Sandbox Code Playgroud)