dom.ts 1001 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. }