getScrollBarSize.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /* eslint-disable no-param-reassign */
  2. var cached;
  3. export default function getScrollBarSize(fresh) {
  4. if (typeof document === 'undefined') {
  5. return 0;
  6. }
  7. if (fresh || cached === undefined) {
  8. var inner = document.createElement('div');
  9. inner.style.width = '100%';
  10. inner.style.height = '200px';
  11. var outer = document.createElement('div');
  12. var outerStyle = outer.style;
  13. outerStyle.position = 'absolute';
  14. outerStyle.top = '0';
  15. outerStyle.left = '0';
  16. outerStyle.pointerEvents = 'none';
  17. outerStyle.visibility = 'hidden';
  18. outerStyle.width = '200px';
  19. outerStyle.height = '150px';
  20. outerStyle.overflow = 'hidden';
  21. outer.appendChild(inner);
  22. document.body.appendChild(outer);
  23. var widthContained = inner.offsetWidth;
  24. outer.style.overflow = 'scroll';
  25. var widthScroll = inner.offsetWidth;
  26. if (widthContained === widthScroll) {
  27. widthScroll = outer.clientWidth;
  28. }
  29. document.body.removeChild(outer);
  30. cached = widthContained - widthScroll;
  31. }
  32. return cached;
  33. }
  34. function ensureSize(str) {
  35. var match = str.match(/^(.*)px$/);
  36. var value = Number(match === null || match === void 0 ? void 0 : match[1]);
  37. return Number.isNaN(value) ? getScrollBarSize() : value;
  38. }
  39. export function getTargetScrollBarSize(target) {
  40. if (typeof document === 'undefined' || !target || !(target instanceof Element)) {
  41. return {
  42. width: 0,
  43. height: 0
  44. };
  45. }
  46. var _getComputedStyle = getComputedStyle(target, '::-webkit-scrollbar'),
  47. width = _getComputedStyle.width,
  48. height = _getComputedStyle.height;
  49. return {
  50. width: ensureSize(width),
  51. height: ensureSize(height)
  52. };
  53. }