tavern-waterfall-layout
Version:
Waterfall flow layout javascript
47 lines (43 loc) • 1.43 kB
JavaScript
class WaterFall {
constructor(container, options) {
this.gap = options.gap || 0 // 间距
this.container = container // 容器
this.heightAll = [] // 每个子元素的高度
this.items = container.children
}
init() {
if (this.items.length === 0) return // 如果没有子元素,直接滚犊子
const gap = this.gap
const pageWidth = this.container.offsetWidth
const itemWidth = this.items[0].offsetWidth
const columns = pageWidth / (itemWidth + gap) // 总计多少列
for (let i = 0; i < this.items.length; i++) {
let top, left
if (i < columns) {
this.items[i].style.top = 0
this.items[i].style.left = (itemWidth + gap) * i + 'px'
this.heightAll.push(this.items[i].offsetHeight)
} else {
const minIndex = this.getMinIndex(this.heightAll)
top = this.heightAll[minIndex] + gap
left = this.items[minIndex].offsetLeft
this.heightAll[minIndex] += this.items[i].offsetHeight + gap
}
this.items[i].style.position = 'absolute'
this.items[i].style.top = top + 'px'
this.items[i].style.left = left + 'px'
}
}
getMinIndex(heightAll) {
let minIndex = 0
let min = heightAll[minIndex]
for (let i = 1; i < heightAll.length; i++) {
if (heightAll[i] < min) {
min = heightAll[i]
minIndex = i
}
}
return minIndex
}
}
export default WaterFall