How can I get the browser's scrollbar sizes?

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

    It seems to work, but maybe there is a simpler solution that works in all browsers?

    // 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;
    }

提交回复
热议问题