div scrollbar width

后端 未结 4 1443
醉酒成梦
醉酒成梦 2020-12-29 15:49

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.

相关标签:
4条回答
  • 2020-12-29 16:06

    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();
    
    0 讨论(0)
  • 2020-12-29 16:07

    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);
    }
    
    0 讨论(0)
  • 2020-12-29 16:18

    try this

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

    0 讨论(0)
  • 2020-12-29 16:23

    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 讨论(0)
提交回复
热议问题