div scrollbar width

后端 未结 4 1467
醉酒成梦
醉酒成梦 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条回答
  •  Happy的楠姐
    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);
    }
    

提交回复
热议问题