admin管理员组

文章数量:1391955

I encountered a problem where I need to know of the height of horizontal scrollbar.

This Q&A suggests that you should use clientHeight property and calculate difference. Unfortunately this does not work anymore as is evident here /

So how can I get the height of scrollbar?

EDIT: OSX does not differentiate between offsetHeight and clientHeight.

html:

<div id="wrapper">
  <div id="content"></div>
</div>

css:

#wrapper{
  height:100px;
  width:100%;
  overflow-x:auto;
}
#content{
  height:100%;
  width:200%;
  background:linear-gradient(to right, red , yellow);
}

I encountered a problem where I need to know of the height of horizontal scrollbar.

This Q&A suggests that you should use clientHeight property and calculate difference. Unfortunately this does not work anymore as is evident here https://jsfiddle/fn8naww8/

So how can I get the height of scrollbar?

EDIT: OSX does not differentiate between offsetHeight and clientHeight.

html:

<div id="wrapper">
  <div id="content"></div>
</div>

css:

#wrapper{
  height:100px;
  width:100%;
  overflow-x:auto;
}
#content{
  height:100%;
  width:200%;
  background:linear-gradient(to right, red , yellow);
}
Share Improve this question edited Apr 28, 2018 at 11:53 sanjihan asked Apr 28, 2018 at 11:38 sanjihansanjihan 6,08616 gold badges66 silver badges136 bronze badges 3
  • offsetHeight returns 100px for main div and because of scroll 83 for inner – user8517929 Commented Apr 28, 2018 at 11:47
  • thanks, I believe that only works on windows. – sanjihan Commented Apr 28, 2018 at 11:48
  • I have checked with some osx chrome extensions and I posted answer where it works but with osx extensions it shows 100px for both. On windows 83 for content. – user8517929 Commented Apr 28, 2018 at 12:15
Add a ment  | 

3 Answers 3

Reset to default 5

Try with:

var horizontalScrollbarHeight = wrapper.offsetHeight - wrapper.clientHeight; 

or like:

var horizontalScrollbarHeight = wrapper.offsetHeight - parseInt(window.getComputedStyle(wrapper, null).getPropertyValue("height"), 10); 

Both will return ~17 if the scrollbar size was not altered by CSS like by using ::-webkit-scrollbar

https://developer.mozilla/en-US/docs/Web/API/Window/getComputedStyle

console.log(window.getComputedStyle(document.querySelector("#wrapper")).height);
console.log(window.getComputedStyle(document.querySelector("#content")).height);
*{
  box-sizing: border-box;
}
#wrapper{
  height:100px;
  width:100%;
  overflow-x:auto;
}
#content{
  height:100%;
  width:200%;
  background:linear-gradient(to right, red , yellow);
}
<div id="wrapper">
  <div id="content"></div>
</div>

This will return 100px for wrapper and 83px for inner.

There is a magic number: “17px”. Seems this height/width does not change even if you resize the browser window. And it works on Chrome fine with my test.

本文标签: javascriptget the height of horizontal scrollbarStack Overflow