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 07:59
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
    };
},

Tested in Chrome, FF, IE8, IE11.

查看更多
旧时光的记忆
3楼-- · 2018-12-31 08:00
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;
  }
查看更多
闭嘴吧你
4楼-- · 2018-12-31 08:01

You can determine window scroll bar with document as below using jquery + javascript:

var scrollbarWidth = ($(document).width() - window.innerWidth);
console.info("Window Scroll Bar Width=" + scrollbarWidth );
查看更多
ら面具成の殇う
5楼-- · 2018-12-31 08:07

if you are looking for a simple operation, just mix plain dom js and jquery,

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

returns the size of current page scrollbar. (if it is visible or else will return 0)

查看更多
明月照影归
6楼-- · 2018-12-31 08:08

The way Antiscroll.js does it in it's code is:

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

The code is from here: https://github.com/LearnBoost/antiscroll/blob/master/antiscroll.js#L447

查看更多
看风景的人
7楼-- · 2018-12-31 08:09

If you already have an element with scrollbars on it use:

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

If there is no horzintscrollbar present the function will retun 0

查看更多
登录 后发表回答