How to reliably get screen width WITH the scrollbar

前端 未结 9 1096
抹茶落季
抹茶落季 2020-12-03 21:38

Is there a way to reliably tell a browser\'s viewport width that includes the scrollbar, but not the rest of browser window)?

None of the properties listed here tell

相关标签:
9条回答
  • 2020-12-03 22:23

    As long as body is 100%, document.body.scrollWidth will work.

    Demo: http://jsfiddle.net/ThinkingStiff/5j3bY/

    HTML:

    <div id="widths"></div>
    

    CSS:

    body, html
    {
    margin: 0;
    padding: 0;
    width: 100%;
    }
    
    div
    {
    height: 1500px;
    }
    

    Script:

    var widths = 'viewport width (body.scrollWidth): ' 
        + document.body.scrollWidth + '<br />'
        + 'window.innerWidth: ' + window.innerWidth + '<br />';
    
    document.getElementById( 'widths' ).innerHTML = widths;
    

    I put a tall div in the demo to force a scroll bar.

    0 讨论(0)
  • 2020-12-03 22:23

    there is nothing after scrollbar so "rest of the window" is what?

    But yes one way to do it is make another wrapper div in body where everything goes and body has overflow:none; height:100%; width:100%; on it, wrapper div also also has 100% width and height. and overflow to scroll. SO NOW...the width of wrapper would be the width of viewport

    See Example: http://jsfiddle.net/techsin/8fvne9fz/

    html,body {
        height: 100%;
        overflow: hidden;
    }
    
    .wrapper {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    
    0 讨论(0)
  • 2020-12-03 22:23

    With jQuery you can calculate the browser's scrollbar width by getting the width difference when overflow: hidden is set and overflow: scroll is set. The difference in width will be the size of the scrollbar.

    Here is a simple example that shows how you could do this.

    0 讨论(0)
提交回复
热议问题