dom.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. export interface VisibleDomRect {
  2. bottom: number;
  3. height: number;
  4. left: number;
  5. right: number;
  6. top: number;
  7. width: number;
  8. }
  9. /**
  10. * 获取元素可见信息
  11. * @param element
  12. */
  13. export function getElementVisibleRect(
  14. element?: HTMLElement | null | undefined,
  15. ): VisibleDomRect {
  16. if (!element) {
  17. return {
  18. bottom: 0,
  19. height: 0,
  20. left: 0,
  21. right: 0,
  22. top: 0,
  23. width: 0,
  24. };
  25. }
  26. const rect = element.getBoundingClientRect();
  27. const viewHeight = Math.max(
  28. document.documentElement.clientHeight,
  29. window.innerHeight,
  30. );
  31. const top = Math.max(rect.top, 0);
  32. const bottom = Math.min(rect.bottom, viewHeight);
  33. const viewWidth = Math.max(
  34. document.documentElement.clientWidth,
  35. window.innerWidth,
  36. );
  37. const left = Math.max(rect.left, 0);
  38. const right = Math.min(rect.right, viewWidth);
  39. return {
  40. bottom,
  41. height: Math.max(0, bottom - top),
  42. left,
  43. right,
  44. top,
  45. width: Math.max(0, right - left),
  46. };
  47. }
  48. export function getScrollbarWidth() {
  49. const scrollDiv = document.createElement('div');
  50. scrollDiv.style.visibility = 'hidden';
  51. scrollDiv.style.overflow = 'scroll';
  52. scrollDiv.style.position = 'absolute';
  53. scrollDiv.style.top = '-9999px';
  54. document.body.append(scrollDiv);
  55. const innerDiv = document.createElement('div');
  56. scrollDiv.append(innerDiv);
  57. const scrollbarWidth = scrollDiv.offsetWidth - innerDiv.offsetWidth;
  58. scrollDiv.remove();
  59. return scrollbarWidth;
  60. }
  61. export function needsScrollbar() {
  62. const doc = document.documentElement;
  63. const body = document.body;
  64. // 检查 body 的 overflow-y 样式
  65. const overflowY = window.getComputedStyle(body).overflowY;
  66. // 如果明确设置了需要滚动条的样式
  67. if (overflowY === 'scroll' || overflowY === 'auto') {
  68. return doc.scrollHeight > window.innerHeight;
  69. }
  70. // 在其他情况下,根据 scrollHeight 和 innerHeight 比较判断
  71. return doc.scrollHeight > window.innerHeight;
  72. }
  73. export function triggerWindowResize(): void {
  74. // 创建一个新的 resize 事件
  75. const resizeEvent = new Event('resize');
  76. // 触发 window 的 resize 事件
  77. window.dispatchEvent(resizeEvent);
  78. }