Как я могу получить размеры прокрутки браузера?

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

Ответ 1

Из Alexandre Gomes Blog Я не пробовал. Дайте мне знать, если это сработает для вас.

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

Ответ 2

Используя jQuery, вы можете сократить ответ Мэтью Вина на:

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

Ответ 3

Это только script, который я нашел, который работает в браузерах 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-03-28 в Windows 7 в последних версиях FF, Chrome, IE и Safari и 100% работает.

источник: http://benalman.com/projects/jquery-misc-plugins/#scrollbarwidth

Ответ 4

Если вы ищете простую операцию, просто смешайте plain dom js и jquery,

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

возвращает размер текущей полосы прокрутки страницы. (если он виден или вернется 0)

Ответ 5

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

Ответ 6

Я нашел простое решение, которое работает для элементов внутри страницы, а не самой страницы: $('#element')[0].offsetHeight - $('#element')[0].clientHeight

Это возвращает высоту полосы прокрутки по оси x.

Ответ 7

Если у вас уже есть элемент с полосами прокрутки, используйте:

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

Если нет текущей строки прокрутки, функция будет перенастраивать 0

Ответ 8

Вы можете определить полосу прокрутки window с помощью document, как показано ниже, с помощью jquery + javascript:

var scrollbarWidth = ($(document).width() - window.innerWidth);
console.info("Window Scroll Bar Width=" + scrollbarWidth );

Ответ 9

Из Блог Дэвида Уолша:

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

Ответ 10

Для меня самый полезный способ был

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

с ванильным JavaScript.

enter image description here

Ответ 11

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

Ответ 12

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.

Ответ 13

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

Ответ 14

Создайте пустой 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 строки кода.

Ответ 15

С 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 лучше ответить.

Ответ 16

Это отличный ответ: fooobar.com/questions/10498/...

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

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

Ответ 17

Это решение для взлома жизни даст вам возможность найти ширину прокрутки браузера (ванильный 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;
}

Ответ 18

Создайте пустой 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 всегда будет иметь ширину/высоту полосы прокрутки.

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

Ответ 19

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

function getScrollbarWidth() {
  return (window.innerWidth - document.documentElement.clientWidth);
}