div scrollbar width

后端 未结 4 1462
醉酒成梦
醉酒成梦 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 = $('
    '); $('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();
    

提交回复
热议问题