How can I get the browser's scrollbar sizes?

后端 未结 23 2234
孤街浪徒
孤街浪徒 2020-11-22 06:08

How can I determine the height of a horizontal scrollbar, or the width of a vertical one, in JavaScript?

23条回答
  •  长发绾君心
    2020-11-22 06:15

    Create an empty div and make sure it's present on all pages (i.e. by putting it in the header template).

    Give it this styling:

    #scrollbar-helper {
        // Hide it beyond the borders of the browser
        position: absolute;
        top: -100%;
    
        // Make sure the scrollbar is always visible
        overflow: scroll;
    }
    

    Then simply check for the size of #scrollbar-helper with Javascript:

    var scrollbarWidth = document.getElementById('scrollbar-helper').offsetWidth;
    var scrollbarHeight = document.getElementById('scrollbar-helper').offsetHeight;
    

    No need to calculate anything, as this div will always have the width and height of the scrollbar.

    The only downside is that there will be an empty div in your templates.. But on the other hand, your Javascript files will be cleaner, as this only takes 1 or 2 lines of code.

提交回复
热议问题