How can I get the browser's scrollbar sizes?

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

    Here's the more concise and easy to read solution based on offset width difference:

    function getScrollbarWidth(): number {
    
      // Creating invisible container
      const outer = document.createElement('div');
      outer.style.visibility = 'hidden';
      outer.style.overflow = 'scroll'; // forcing scrollbar to appear
      outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
      document.body.appendChild(outer);
    
      // Creating inner element and placing it in the container
      const inner = document.createElement('div');
      outer.appendChild(inner);
    
      // Calculating difference between container's full width and the child width
      const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);
    
      // Removing temporary elements from the DOM
      outer.parentNode.removeChild(outer);
    
      return scrollbarWidth;
    
    }
    

    See the JSFiddle.

提交回复
热议问题