waterFallBox.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233
  1. function fallBox(props: { ref: { children?: any, offsetWidth: number, style: any }, childrenWidth: number }) {
  2. let time = setTimeout(() => {
  3. let { ref: { children }, childrenWidth } = props
  4. let bodyW = props.ref.offsetWidth
  5. let column = Math.floor(bodyW / (childrenWidth))
  6. let margin = Math.floor((bodyW / column - childrenWidth) )
  7. let allH: number[] = []//所有列的高度
  8. let marginB = margin > 20 ? margin / 2 : margin
  9. children.forEach((chi: HTMLElement, index: number) => {
  10. let h = chi.offsetHeight
  11. if (index < column) {
  12. allH.push(h)
  13. chi.style.left = (childrenWidth + margin) * index + 'px'
  14. chi.style.top = '0px'
  15. chi.style.width = childrenWidth + 'px'
  16. chi.style.position = 'absolute'
  17. } else {
  18. let minH: number = Math.min(...allH)//取当前最小高度的children的值
  19. let eq = allH.indexOf(minH)//取当前最小高度children的位置
  20. allH[eq] = allH[eq] + h + marginB//更新列的高
  21. chi.style.left = eq === 0 ? '0px' : (childrenWidth + margin) * eq + 'px'
  22. chi.style.top = minH ? minH + marginB + 'px' : '0px'
  23. chi.style.width = childrenWidth + 'px'
  24. chi.style.position = 'absolute'
  25. }
  26. })
  27. props.ref.style.height = Math.max(...allH) + 20 + 'px'
  28. clearTimeout(time)
  29. }, 600)
  30. }
  31. export default fallBox