How can I get the browser's scrollbar sizes?

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

    I made an updated version of @Matthew Vines answer.

    It's easier to read, easier to understand. It doesn't require an inner element. The element created to get the scroll bar width has a 100% height/width so it doesn't create any visible scroll bar on the body on lower end PCs/mobiles which could take a bit more time to create the element, get the widths, and finally remove the element.

    const getScrollBarWidth = () => {
      const e = document.createElement('div');
      Object.assign(e.style, {
        width: '100%',
        height: '100%',
        overflow: 'scroll',
        position: 'absolute',
        visibility: 'hidden',
        top: '0',
        left: '0',
      });
    
      document.body.appendChild(e);
    
      const scrollbarWidth = e.offsetWidth - e.clientWidth;
    
      document.body.removeChild(e);
    
      return scrollbarWidth;
    };
    
    console.log(getScrollBarWidth());
    

    I do recommend to check for the scroll bar width only once, at page load (except if it doesn't fit your needs) then store the result in a state/variable.

提交回复
热议问题