How can I get the browser's scrollbar sizes?

2018-12-31 07:49发布

How can I determine the height of a horizontal scrollbar, or the width of a vertical one, in JavaScript?

17条回答
皆成旧梦
2楼-- · 2018-12-31 08:12

Using jQuery, you can shorten Matthew Vines answer to:

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楼-- · 2018-12-31 08:12
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; 
} 
查看更多
泪湿衣
4楼-- · 2018-12-31 08:13

I found a simple solution that works for elements inside of the page, instead of the page itself: $('#element')[0].offsetHeight - $('#element')[0].clientHeight

This returns the height of the x-axis scrollbar.

查看更多
十年一品温如言
5楼-- · 2018-12-31 08:13

For me, the most useful way was

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

with vanilla JavaScript.

enter image description here

查看更多
初与友歌
6楼-- · 2018-12-31 08:14

This life-hack decision will give you opportunity to find browser scrollY width (vanilla JavaScript). Using this example you can get scrollY width on any element including those elements that shouldn't have to have scroll according to your current design conception,:

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;
}
查看更多
登录 后发表回答