parent.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import { computed, onMounted, ref } from 'vue'
  2. /**
  3. * 获取真实DOM的高度
  4. * @returns [heightRef, VMRef, readyRef]
  5. */
  6. export const getVMDomWH = attr => {
  7. const origin = ref(0)
  8. const domRef = ref(null)
  9. const ready = ref(false)
  10. const referWH = () => {
  11. origin.value = 0
  12. ready.value = false
  13. if (domRef.value) {
  14. setTimeout(() => {
  15. origin.value = attr === 'width' ? domRef.value.offsetWidth : domRef.value.offsetHeight
  16. setTimeout(() => (ready.value = true))
  17. })
  18. }
  19. }
  20. onMounted(referWH)
  21. return [origin, domRef, ready, referWH]
  22. }
  23. /**
  24. * 生成切换高度的方法
  25. * @returns [VMRef, fn, maxHeightRef, originHeightRef, showRef, readyRef]
  26. */
  27. export const changeWHFactory = (isShow = false, attr = 'height') => {
  28. const [origin, domRef, ready, referWH] = getVMDomWH(attr)
  29. const max = ref(0)
  30. const show = computed({
  31. get: () => {
  32. return max.value == origin.value
  33. },
  34. set: val => {
  35. max.value = val ? origin.value : 0
  36. },
  37. })
  38. const changeShow = (val = !show.value) => {
  39. show.value = val
  40. }
  41. onMounted(() => {
  42. show.value = isShow
  43. })
  44. return [domRef, changeShow, max, origin, show, ready, referWH]
  45. }
  46. /**
  47. * 获取父级滚动
  48. * @param {*} node
  49. * @returns
  50. */
  51. export const getScrollParent = (node: HTMLElement): HTMLElement => {
  52. if (node == null) {
  53. return null
  54. }
  55. if (node === document.documentElement) {
  56. return node
  57. }
  58. const cssScrollY = getComputedStyle(node).overflowY
  59. const cssScrollX = getComputedStyle(node).overflowX
  60. if (node.scrollHeight > node.clientHeight || cssScrollY === 'auto' || cssScrollY === 'scroll' || cssScrollX === 'auto' || cssScrollX === 'scroll') {
  61. return node
  62. } else {
  63. return getScrollParent(node.parentNode)
  64. }
  65. }
  66. /**
  67. * 获取所有父级滚动
  68. * @param {*} origin
  69. * @param {*} target
  70. */
  71. export const getScrollParents = (origin, target) => {
  72. const parents = []
  73. let temporary = origin
  74. while (temporary && temporary !== target && temporary !== document.documentElement && target.contains(temporary)) {
  75. const scrollParent = getScrollParent(temporary)
  76. if (scrollParent) {
  77. if (scrollParent !== origin) {
  78. parents.push(scrollParent)
  79. }
  80. temporary = scrollParent.parentNode
  81. } else {
  82. break
  83. }
  84. }
  85. return parents
  86. }