How can I get the browser's scrollbar sizes?

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

    This life-hack decision will give you opportunity to find browser scrollY width (vanilla JavaScript). Using this example you can get scrollY width on any element including those elements that shouldn't have to have scroll according to your current design conception,:

    getComputedScrollYWidth     (el)  {
    
      let displayCSSValue  ; // CSS value
      let overflowYCSSValue; // CSS value
    
      // SAVE current original STYLES values
      {
        displayCSSValue   = el.style.display;
        overflowYCSSValue = el.style.overflowY;
      }
    
      // SET TEMPORALLY styles values
      {
        el.style.display   = 'block';
        el.style.overflowY = 'scroll';
      }
    
      // SAVE SCROLL WIDTH of the current browser.
      const scrollWidth = el.offsetWidth - el.clientWidth;
    
      // REPLACE temporally STYLES values by original
      {
        el.style.display   = displayCSSValue;
        el.style.overflowY = overflowYCSSValue;
      }
    
      return scrollWidth;
    }
    

提交回复
热议问题