dom.ts 509 B

123456789101112131415161718192021222324
  1. /**
  2. * 获取元素可见高度
  3. * @param element
  4. * @returns
  5. */
  6. function getElementVisibleHeight(
  7. element?: HTMLElement | null | undefined,
  8. ): number {
  9. if (!element) {
  10. return 0;
  11. }
  12. const rect = element.getBoundingClientRect();
  13. const viewHeight = Math.max(
  14. document.documentElement.clientHeight,
  15. window.innerHeight,
  16. );
  17. const top = Math.max(rect.top, 0);
  18. const bottom = Math.min(rect.bottom, viewHeight);
  19. return Math.max(0, bottom - top);
  20. }
  21. export { getElementVisibleHeight };