177

如何在 JavaScript 中确定水平滚动条的高度或垂直滚动​​条的宽度?

4

25 回答 25

144

来自Alexandre Gomes 博客 ,我没有尝试过。请让我知道这对你有没有用。

function getScrollBarWidth () {
  var inner = document.createElement('p');
  inner.style.width = "100%";
  inner.style.height = "200px";

  var outer = document.createElement('div');
  outer.style.position = "absolute";
  outer.style.top = "0px";
  outer.style.left = "0px";
  outer.style.visibility = "hidden";
  outer.style.width = "200px";
  outer.style.height = "150px";
  outer.style.overflow = "hidden";
  outer.appendChild (inner);

  document.body.appendChild (outer);
  var w1 = inner.offsetWidth;
  outer.style.overflow = 'scroll';
  var w2 = inner.offsetWidth;
  if (w1 == w2) w2 = outer.clientWidth;

  document.body.removeChild (outer);

  return (w1 - w2);
};
于 2009-06-12T14:37:09.190 回答
82

使用 jQuery,您可以将 Matthew Vines 的答案缩短为:

function getScrollBarWidth () {
    var $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
        widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
    $outer.remove();
    return 100 - widthWithScroll;
};
于 2013-09-25T21:10:19.870 回答
26

如果你正在寻找一个简单的操作,只需混合普通的 dom js 和 jquery,

var swidth=(window.innerWidth-$(window).width());

返回当前页面滚动条的大小。(如果它是可见的,否则将返回 0)

于 2014-04-01T06:33:23.367 回答
25

这只是我找到的脚本,它在 webkit 浏览器中工作...... :)

$.scrollbarWidth = function() {
  var parent, child, width;

  if(width===undefined) {
    parent = $('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body');
    child=parent.children();
    width=child.innerWidth()-child.height(99).innerWidth();
    parent.remove();
  }

 return width;
};

最小化版本:

$.scrollbarWidth=function(){var a,b,c;if(c===undefined){a=$('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body');b=a.children();c=b.innerWidth()-b.height(99).innerWidth();a.remove()}return c};

你必须在文件准备好时调用它......所以

$(function(){ console.log($.scrollbarWidth()); });

于 2012 年 3 月 28 日在最新的 FF、Chrome、IE 和 Safari 的 Windows 7 上测试,并且 100% 正常工作。

来源:http ://benalman.com/projects/jquery-misc-plugins/#scrollbarwidth

于 2012-03-28T13:46:29.107 回答
20

对我来说,最有用的方法是

(window.innerWidth - document.getElementsByTagName('html')[0].clientWidth)

使用香草 JavaScript。

在此处输入图像描述

于 2018-04-12T10:53:59.147 回答
17
window.scrollBarWidth = function() {
  document.body.style.overflow = 'hidden'; 
  var width = document.body.clientWidth;
  document.body.style.overflow = 'scroll'; 
  width -= document.body.clientWidth; 
  if(!width) width = document.body.offsetWidth - document.body.clientWidth;
  document.body.style.overflow = ''; 
  return width; 
} 
于 2009-06-12T19:59:57.730 回答
9

我找到了一个简单的解决方案,适用于页面内部的元素,而不是页面本身: $('#element')[0].offsetHeight - $('#element')[0].clientHeight

这将返回 x 轴滚动条的高度。

于 2014-07-23T15:24:56.660 回答
8

来自大卫沃尔什的博客

// Create the measurement node
var scrollDiv = document.createElement("div");
scrollDiv.className = "scrollbar-measure";
document.body.appendChild(scrollDiv);

// Get the scrollbar width
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
console.info(scrollbarWidth); // Mac:  15

// Delete the DIV 
document.body.removeChild(scrollDiv);
.scrollbar-measure {
	width: 100px;
	height: 100px;
	overflow: scroll;
	position: absolute;
	top: -9999px;
}

在我的网站上给了我 17 个,在 Stackoverflow 上给了我 14 个。

于 2016-06-13T02:00:53.870 回答
5

您可以使用 jquery + javascript 确定window滚动条,document如下所示:

var scrollbarWidth = ($(document).width() - window.innerWidth);
console.info("Window Scroll Bar Width=" + scrollbarWidth );
于 2016-06-10T09:12:48.497 回答
5

这应该可以解决问题,不是吗?

function getScrollbarWidth() {
  return (window.innerWidth - document.documentElement.clientWidth);
}
于 2019-02-04T08:24:28.267 回答
4

如果您已经有一个带有滚动条的元素,请使用:

function getScrollbarHeight(el) {
    return el.getBoundingClientRect().height - el.scrollHeight;
};

如果不存在 horzintscrollbar,该函数将返回 0

于 2015-10-05T11:33:02.127 回答
3

Antiscroll.js在它的代码中这样做的方式是:

function scrollbarSize () {
  var div = $(
      '<div class="antiscroll-inner" style="width:50px;height:50px;overflow-y:scroll;'
    + 'position:absolute;top:-200px;left:-200px;"><div style="height:100px;width:100%"/>'
    + '</div>'
  );

  $('body').append(div);
  var w1 = $(div).innerWidth();
  var w2 = $('div', div).innerWidth();
  $(div).remove();

  return w1 - w2;
};

代码来自这里:https ://github.com/LearnBoost/antiscroll/blob/master/antiscroll.js#L447

于 2014-03-28T08:08:11.127 回答
3
detectScrollbarWidthHeight: function() {
    var div = document.createElement("div");
    div.style.overflow = "scroll";
    div.style.visibility = "hidden";
    div.style.position = 'absolute';
    div.style.width = '100px';
    div.style.height = '100px';
    document.body.appendChild(div);

    return {
        width: div.offsetWidth - div.clientWidth,
        height: div.offsetHeight - div.clientHeight
    };
},

在 Chrome、FF、IE8、IE11 中测试。

于 2014-04-10T16:40:01.253 回答
3
function getScrollBarWidth() {
    return window.innerWidth - document.documentElement.clientWidth;
}

大多数浏览器使用 15px 作为滚动条宽度

于 2020-02-25T06:42:13.720 回答
2

创建一个空白div并确保它出现在所有页面上(即通过将其放入header模板中)。

给它这个样式:

#scrollbar-helper {
    // Hide it beyond the borders of the browser
    position: absolute;
    top: -100%;

    // Make sure the scrollbar is always visible
    overflow: scroll;
}

然后只需检查#scrollbar-helperJavascript 的大小:

var scrollbarWidth = document.getElementById('scrollbar-helper').offsetWidth;
var scrollbarHeight = document.getElementById('scrollbar-helper').offsetHeight;

无需计算任何东西,因为这div将始终具有的widthheightscrollbar

唯一的缺点是您的模板中会有一个空白div。但另一方面,您的 Javascript 文件会更干净,因为这只需要 1 或 2 行代码。

于 2018-03-17T11:44:41.283 回答
1
function getWindowScrollBarHeight() {
    let bodyStyle = window.getComputedStyle(document.body);
    let fullHeight = document.body.scrollHeight;
    let contentsHeight = document.body.getBoundingClientRect().height;
    let marginTop = parseInt(bodyStyle.getPropertyValue('margin-top'), 10);
    let marginBottom = parseInt(bodyStyle.getPropertyValue('margin-bottom'), 10);
    return fullHeight - contentHeight - marginTop - marginBottom;
  }
于 2016-09-26T22:48:01.090 回答
0

使用 jquery(仅在 Firefox 中测试):

function getScrollBarHeight() {
    var jTest = $('<div style="display:none;width:50px;overflow: scroll"><div style="width:100px;"><br /><br /></div></div>');
    $('body').append(jTest);
    var h = jTest.innerHeight();
    jTest.css({
        overflow: 'auto',
        width: '200px'
    });
    var h2 = jTest.innerHeight();
    return h - h2;
}

function getScrollBarWidth() {
    var jTest = $('<div style="display:none;height:50px;overflow: scroll"><div style="height:100px;"></div></div>');
    $('body').append(jTest);
    var w = jTest.innerWidth();
    jTest.css({
        overflow: 'auto',
        height: '200px'
    });
    var w2 = jTest.innerWidth();
    return w - w2;
}

但我实际上更喜欢@Steve 的回答。

于 2014-09-23T11:14:14.607 回答
0

这是一个很好的答案: https ://stackoverflow.com/a/986977/5914609

但是在我的情况下它不起作用。我花了几个小时寻找解决方案。
最后我回到了上面的代码并添加了 !important 到每种样式。它奏效了。
我无法在原始答案下方添加评论。所以这里是修复:

function getScrollBarWidth () {
  var inner = document.createElement('p');
  inner.style.width = "100% !important";
  inner.style.height = "200px !important";

  var outer = document.createElement('div');
  outer.style.position = "absolute !important";
  outer.style.top = "0px !important";
  outer.style.left = "0px !important";
  outer.style.visibility = "hidden !important";
  outer.style.width = "200px !important";
  outer.style.height = "150px !important";
  outer.style.overflow = "hidden !important";
  outer.appendChild (inner);

  document.body.appendChild (outer);
  var w1 = inner.offsetWidth;
  outer.style.overflow = 'scroll !important';
  var w2 = inner.offsetWidth;
  if (w1 == w2) w2 = outer.clientWidth;

  document.body.removeChild (outer);

  return (w1 - w2);
};
于 2016-04-23T11:10:23.617 回答
0

这个生命黑客决定将使您有机会找到浏览器滚动宽度(vanilla JavaScript)。使用此示例,您可以在任何元素上获得 scrollY 宽度,包括根据您当前的设计概念不应该滚动的那些元素,:

getComputedScrollYWidth     (el)  {

  let displayCSSValue  ; // CSS value
  let overflowYCSSValue; // CSS value

  // SAVE current original STYLES values
  {
    displayCSSValue   = el.style.display;
    overflowYCSSValue = el.style.overflowY;
  }

  // SET TEMPORALLY styles values
  {
    el.style.display   = 'block';
    el.style.overflowY = 'scroll';
  }

  // SAVE SCROLL WIDTH of the current browser.
  const scrollWidth = el.offsetWidth - el.clientWidth;

  // REPLACE temporally STYLES values by original
  {
    el.style.display   = displayCSSValue;
    el.style.overflowY = overflowYCSSValue;
  }

  return scrollWidth;
}
于 2017-07-11T10:00:49.423 回答
0

这是基于偏移宽度差异的更简洁易读的解决方案:

function getScrollbarWidth(): number {

  // 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;

}

请参阅JSFiddle

于 2019-05-29T11:35:55.493 回答
0

已经在我的库中编码,所以这里是:

var vScrollWidth = window.screen.width - window.document.documentElement.clientWidth;

我应该提一下,jQuery$(window).width()也可以用来代替window.document.documentElement.clientWidth.

如果您在右侧的 Firefox 中打开开发人员工具,它不起作用,但如果在底部打开开发人员窗口,它会克服它!

window.screen支持quirksmode.org

玩得开心!

于 2019-11-26T10:33:55.917 回答
0

它似乎有效,但也许有一个更简单的解决方案适用于所有浏览器?

// Create the measurement node
var scrollDiv = document.createElement("div");
scrollDiv.className = "scrollbar-measure";
document.body.appendChild(scrollDiv);

// Get the scrollbar width
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
console.info(scrollbarWidth); // Mac:  15

// Delete the DIV 
document.body.removeChild(scrollDiv);
.scrollbar-measure {
	width: 100px;
	height: 100px;
	overflow: scroll;
	position: absolute;
	top: -9999px;
}

于 2020-06-02T19:43:27.097 回答
0

我制作了@Matthew Vines 答案的更新版本。

它更容易阅读,更容易理解。它不需要内部元素。为获取滚动条宽度而创建的元素具有 100% 的高度/宽度,因此它不会在低端 PC/手机的主体上创建任何可见的滚动条,这可能需要更多时间来创建元素,获取宽度,最后移除元素。

const getScrollBarWidth = () => {
  const e = document.createElement('div');
  Object.assign(e.style, {
    width: '100%',
    height: '100%',
    overflow: 'scroll',
    position: 'absolute',
    visibility: 'hidden',
    top: '0',
    left: '0',
  });

  document.body.appendChild(e);

  const scrollbarWidth = e.offsetWidth - e.clientWidth;

  document.body.removeChild(e);

  return scrollbarWidth;
};

console.log(getScrollBarWidth());

我建议只检查一次滚动条宽度,在页面加载时(除非它不符合您的需要),然后将结果存储在状态/变量中。

于 2020-08-04T07:56:23.333 回答
0

我在material-ui代码中找到了该解决方案,它对我有用。

const scrollbarWidth = window.innerWidth -  document.querySelector('body').clientWidth;
于 2021-07-05T15:41:25.097 回答
0

您可以使用此解决方案来查找网页内任何元素的滚动条宽度,而不是网页本身。您还可以通过将其与宽度相关的属性替换为与高度相关的对应属性来重写它以在水平滚动条的情况下为滚动条高度工作。

offsetWidth属性返回内容、内边距、边框和滚动条(如果有的话)的总宽度。然而,clientWidth属性仅返回内容和填充的总宽度。

因此,如果我们clientWidth从 中减去水平边框offsetWidth,我们将剩下滚动条的宽度。也就是说,如果有滚动条,我们就会得到滚动条的宽度。但是如果没有任何滚动条,我们会得到0.

const element = document.querySelector("div");
const elementStyle = window.getComputedStyle(element);
const horizontalBorder = parseFloat(elementStyle.borderLeftWidth) + parseFloat(elementStyle.borderRightWidth);
const scrollbarWidth = element.offsetWidth - element.clientWidth - horizontalBorder + "px";
于 2021-07-11T07:16:57.440 回答