How can I get the browser's scrollbar sizes?

后端 未结 23 2219
孤街浪徒
孤街浪徒 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:34

    if you are looking for a simple operation, just mix plain dom js and jquery,

    var swidth=(window.innerWidth-$(window).width());
    

    returns the size of current page scrollbar. (if it is visible or else will return 0)

    0 讨论(0)
  • 2020-11-22 06:34

    I found a simple solution that works for elements inside of the page, instead of the page itself: $('#element')[0].offsetHeight - $('#element')[0].clientHeight

    This returns the height of the x-axis scrollbar.

    0 讨论(0)
  • 2020-11-22 06:35

    This is only script I've found, which is working in webkit browsers ... :)

    $.scrollbarWidth = function() {
      var parent, child, width;
    
      if(width===undefined) {
        parent = $('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body');
        child=parent.children();
        width=child.innerWidth()-child.height(99).innerWidth();
        parent.remove();
      }
    
     return width;
    };
    

    Minimized version:

    $.scrollbarWidth=function(){var a,b,c;if(c===undefined){a=$('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body');b=a.children();c=b.innerWidth()-b.height(99).innerWidth();a.remove()}return c};
    

    And you have to call it when document is ready ... so

    $(function(){ console.log($.scrollbarWidth()); });
    

    Tested 2012-03-28 on Windows 7 in latest FF, Chrome, IE & Safari and 100% working.

    source: http://benalman.com/projects/jquery-misc-plugins/#scrollbarwidth

    0 讨论(0)
  • 2020-11-22 06:35

    This should do the trick, no?

    function getScrollbarWidth() {
      return (window.innerWidth - document.documentElement.clientWidth);
    }
    
    0 讨论(0)
  • 2020-11-22 06:37

    From David Walsh's blog:

    // Create the measurement node
    var scrollDiv = document.createElement("div");
    scrollDiv.className = "scrollbar-measure";
    document.body.appendChild(scrollDiv);
    
    // Get the scrollbar width
    var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
    console.info(scrollbarWidth); // Mac:  15
    
    // Delete the DIV 
    document.body.removeChild(scrollDiv);
    .scrollbar-measure {
    	width: 100px;
    	height: 100px;
    	overflow: scroll;
    	position: absolute;
    	top: -9999px;
    }

    Gives me 17 on my website, 14 here on Stackoverflow.

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