position.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { isClient } from '@vueuse/core'
  2. export const isInContainer = (
  3. el?: Element,
  4. container?: Element | Window
  5. ): boolean => {
  6. if (!isClient || !el || !container) return false
  7. const elRect = el.getBoundingClientRect()
  8. let containerRect: Pick<DOMRect, 'top' | 'bottom' | 'left' | 'right'>
  9. if (container instanceof Element) {
  10. containerRect = container.getBoundingClientRect()
  11. } else {
  12. containerRect = {
  13. top: 0,
  14. right: window.innerWidth,
  15. bottom: window.innerHeight,
  16. left: 0,
  17. }
  18. }
  19. return (
  20. elRect.top < containerRect.bottom &&
  21. elRect.bottom > containerRect.top &&
  22. elRect.right > containerRect.left &&
  23. elRect.left < containerRect.right
  24. )
  25. }
  26. export const getOffsetTop = (el: HTMLElement) => {
  27. let offset = 0
  28. let parent = el
  29. while (parent) {
  30. offset += parent.offsetTop
  31. parent = parent.offsetParent as HTMLElement
  32. }
  33. return offset
  34. }
  35. export const getOffsetTopDistance = (
  36. el: HTMLElement,
  37. containerEl: HTMLElement
  38. ) => {
  39. return Math.abs(getOffsetTop(el) - getOffsetTop(containerEl))
  40. }
  41. export const getClientXY = (event: MouseEvent | TouchEvent) => {
  42. let clientX: number
  43. let clientY: number
  44. if (event.type === 'touchend') {
  45. clientY = (event as TouchEvent).changedTouches[0].clientY
  46. clientX = (event as TouchEvent).changedTouches[0].clientX
  47. } else if (event.type.startsWith('touch')) {
  48. clientY = (event as TouchEvent).touches[0].clientY
  49. clientX = (event as TouchEvent).touches[0].clientX
  50. } else {
  51. clientY = (event as MouseEvent).clientY
  52. clientX = (event as MouseEvent).clientX
  53. }
  54. return {
  55. clientX,
  56. clientY,
  57. }
  58. }