getScrollBarSize.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* eslint-disable no-param-reassign */
  2. import { removeCSS, updateCSS } from "./Dom/dynamicCSS";
  3. var cached;
  4. function measureScrollbarSize(ele) {
  5. var randomId = "rc-scrollbar-measure-".concat(Math.random().toString(36).substring(7));
  6. var measureEle = document.createElement('div');
  7. measureEle.id = randomId;
  8. // Create Style
  9. var measureStyle = measureEle.style;
  10. measureStyle.position = 'absolute';
  11. measureStyle.left = '0';
  12. measureStyle.top = '0';
  13. measureStyle.width = '100px';
  14. measureStyle.height = '100px';
  15. measureStyle.overflow = 'scroll';
  16. // Clone Style if needed
  17. var fallbackWidth;
  18. var fallbackHeight;
  19. if (ele) {
  20. var targetStyle = getComputedStyle(ele);
  21. measureStyle.scrollbarColor = targetStyle.scrollbarColor;
  22. measureStyle.scrollbarWidth = targetStyle.scrollbarWidth;
  23. // Set Webkit style
  24. var webkitScrollbarStyle = getComputedStyle(ele, '::-webkit-scrollbar');
  25. var width = parseInt(webkitScrollbarStyle.width, 10);
  26. var height = parseInt(webkitScrollbarStyle.height, 10);
  27. // Try wrap to handle CSP case
  28. try {
  29. var widthStyle = width ? "width: ".concat(webkitScrollbarStyle.width, ";") : '';
  30. var heightStyle = height ? "height: ".concat(webkitScrollbarStyle.height, ";") : '';
  31. updateCSS("\n#".concat(randomId, "::-webkit-scrollbar {\n").concat(widthStyle, "\n").concat(heightStyle, "\n}"), randomId);
  32. } catch (e) {
  33. // Can't wrap, just log error
  34. console.error(e);
  35. // Get from style directly
  36. fallbackWidth = width;
  37. fallbackHeight = height;
  38. }
  39. }
  40. document.body.appendChild(measureEle);
  41. // Measure. Get fallback style if provided
  42. var scrollWidth = ele && fallbackWidth && !isNaN(fallbackWidth) ? fallbackWidth : measureEle.offsetWidth - measureEle.clientWidth;
  43. var scrollHeight = ele && fallbackHeight && !isNaN(fallbackHeight) ? fallbackHeight : measureEle.offsetHeight - measureEle.clientHeight;
  44. // Clean up
  45. document.body.removeChild(measureEle);
  46. removeCSS(randomId);
  47. return {
  48. width: scrollWidth,
  49. height: scrollHeight
  50. };
  51. }
  52. export default function getScrollBarSize(fresh) {
  53. if (typeof document === 'undefined') {
  54. return 0;
  55. }
  56. if (fresh || cached === undefined) {
  57. cached = measureScrollbarSize();
  58. }
  59. return cached.width;
  60. }
  61. export function getTargetScrollBarSize(target) {
  62. if (typeof document === 'undefined' || !target || !(target instanceof Element)) {
  63. return {
  64. width: 0,
  65. height: 0
  66. };
  67. }
  68. return measureScrollbarSize(target);
  69. }