计算该浏览器中滚动条的默认宽度

// Slightly modified, but without dependancies:
// https://raw.githubusercontent.com/malte-wessel/react-custom-scrollbars/master/src/utils/getScrollbarWidth.js
let scrollbarWidth: number | null = null;

export function getScrollbarWidth() {
  if (scrollbarWidth !== null) {
    return scrollbarWidth;
  }

  if (typeof document !== 'undefined') {
    const div = document.createElement('div');
    const newStyles = {
      width: '100px',
      height: '100px',
      position: 'absolute',
      top: '-9999px',
      overflow: 'scroll',
      MsOverflowStyle: 'scrollbar',
    };

    Object.keys(newStyles).map((style) => {
      // @ts-ignore
      div.style[style] = newStyles[style];
    });

    document.body.appendChild(div);
    scrollbarWidth = div.offsetWidth - div.clientWidth;
    document.body.removeChild(div);
  } else {
    scrollbarWidth = 0;
  }

  return scrollbarWidth || 0;
}

 

posted @ 2021-07-26 11:28  芥末Yuki  阅读(85)  评论(0编辑  收藏  举报