Как я могу получить размеры полосы прокрутки браузера? - PullRequest
153 голосов
/ 12 июня 2009

Как я могу определить высоту горизонтальной полосы прокрутки или ширину вертикальной полосы прокрутки в JavaScript?

Ответы [ 19 ]

3 голосов
/ 28 марта 2014

Способ 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

3 голосов
/ 10 апреля 2014
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.

1 голос
/ 04 февраля 2019

Это должно сработать, нет?

function getScrollbarWidth() {
  return (window.innerWidth - document.documentElement.clientWidth);
}
1 голос
/ 17 марта 2018

Создайте пустой 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-helper с помощью Javascript:

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

Не нужно ничего вычислять, так как этот div всегда будет иметь width и height из scrollbar.

Единственным недостатком является то, что в ваших шаблонах будет пустой div. Но, с другой стороны, ваши файлы Javascript будут чище, поскольку это займет всего 1 или 2 строки кода.

1 голос
/ 27 сентября 2016
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;
  }
0 голосов
/ 29 мая 2019

Вот более краткое и простое для чтения решение, основанное на разнице ширины смещения:

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 .

0 голосов
/ 11 июля 2017

Это решение поможет вам найти ширину прокрутки браузера (ванильный JavaScript). Используя этот пример, вы можете получить scrollY width для любого элемента , включая те элементы, которые не должны иметь прокрутки в соответствии с вашей текущей концепцией дизайна:

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;
}
0 голосов
/ 23 апреля 2016

Это отличный ответ: https://stackoverflow.com/a/986977/5914609

Однако в моем случае это не сработало. И я часами искал решение.
Наконец, я вернулся к приведенному выше коду и добавил! Важно для каждого стиля. И это сработало.
Я не могу добавить комментарии ниже исходного ответа. Итак, вот исправление:

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);
};
0 голосов
/ 23 сентября 2014

С 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;
}

Но на самом деле мне больше нравится ответ Стива.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...