最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - div scrollbar width - Stack Overflow

programmeradmin3浏览0评论

Is there an easy way to get the width of a scrollbar using javascript / jquery ? I need to get the width of a div that overflows + whatever width the scroll bar is.

Thank you

Is there an easy way to get the width of a scrollbar using javascript / jquery ? I need to get the width of a div that overflows + whatever width the scroll bar is.

Thank you

Share Improve this question asked Sep 21, 2011 at 14:43 G-ManG-Man 7,24118 gold badges73 silver badges101 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 12

if you're using jquery, try this:

function getScrollbarWidth() 
{
    var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div></div>'); 
    $('body').append(div); 
    var w1 = $('div', div).innerWidth(); 
    div.css('overflow-y', 'auto'); 
    var w2 = $('div', div).innerWidth(); 
    $(div).remove(); 
    return (w1 - w2);
}

i'm using this in the project i'm working on and it works like a charm. it gets the scrollbar-width by:

  1. appending a div with overflowing content to the body (in a non-visible area, -200px to top/left)
  2. set overflow to hidden
  3. get the width
  4. set overflow to auto (to get scrollbars)
  5. get the width
  6. substract both widths to get width of the scrollbar

so what you'll have to do is getting the width of your div ($('#mydiv').width()) and add the scrollbar-width:

var completewidth = $('#mydiv').width() + getScrollbarWidth();

try this

$("#myDiv")[0].scrollWidth

Setting a div's overflow to "scroll" automatically adds scrollbars (even if there's nothing inside, the scrollbars will be there, but grey). So just make a div, find the width, set overflow to scroll, and find the new width, and return the difference:

function getScrollBarWidth() {
  var helper = document.createElement('div');
  helper.style = "width: 100px; height: 100px; overflow:hidden;"
  document.body.appendChild(helper);
  var bigger = helper.clientWidth;
  helper.style.overflow = "scroll";
  var smaller = helper.clientWidth;
  document.body.removeChild(helper);
  return(bigger - smaller);
}

Here is a plain javascript version that is way faster.

function getScrollbarWidth() {
  var div, body, W = window.browserScrollbarWidth;
  if (W === undefined) {
    body = document.body, div = document.createElement('div');
    div.innerHTML = '<div style="width: 50px; height: 50px; position: absolute; left: -100px; top: -100px; overflow: auto;"><div style="width: 1px; height: 100px;"></div></div>';
    div = div.firstChild;
    body.appendChild(div);
    W = window.browserScrollbarWidth = div.offsetWidth - div.clientWidth;
    body.removeChild(div);
  }
  return W;
};
发布评论

评论列表(0)

  1. 暂无评论