domUtils.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. export function getBoundingClientRect(element: Element): DOMRect | number {
  2. if (!element || !element.getBoundingClientRect) {
  3. return 0
  4. }
  5. return element.getBoundingClientRect()
  6. }
  7. /**
  8. * Get the left and top offset of the current element
  9. * left: the distance between the leftmost element and the left side of the document
  10. * top: the distance from the top of the element to the top of the document
  11. * right: the distance from the far right of the element to the right of the document
  12. * bottom: the distance from the bottom of the element to the bottom of the document
  13. * rightIncludeBody: the distance between the leftmost element and the right side of the document
  14. * bottomIncludeBody: the distance from the bottom of the element to the bottom of the document
  15. *
  16. * @description:
  17. */
  18. export function getViewportOffset(element: Element): ViewportOffsetResult {
  19. const doc = document.documentElement
  20. const docScrollLeft = doc.scrollLeft
  21. const docScrollTop = doc.scrollTop
  22. const docClientLeft = doc.clientLeft
  23. const docClientTop = doc.clientTop
  24. const { pageXOffset } = window
  25. const { pageYOffset } = window
  26. const box = getBoundingClientRect(element)
  27. const { left: retLeft, top: rectTop, width: rectWidth, height: rectHeight } = box as DOMRect
  28. const scrollLeft = (pageXOffset || docScrollLeft) - (docClientLeft || 0)
  29. const scrollTop = (pageYOffset || docScrollTop) - (docClientTop || 0)
  30. const offsetLeft = retLeft + pageXOffset
  31. const offsetTop = rectTop + pageYOffset
  32. const left = offsetLeft - scrollLeft
  33. const top = offsetTop - scrollTop
  34. const { clientWidth } = window.document.documentElement
  35. const { clientHeight } = window.document.documentElement
  36. return {
  37. left,
  38. top,
  39. right: clientWidth - rectWidth - left,
  40. bottom: clientHeight - rectHeight - top,
  41. rightIncludeBody: clientWidth - left,
  42. bottomIncludeBody: clientHeight - top
  43. }
  44. }