效果图
GitHub源码&Demo: https://github.com/capricorncd/zx-waterfall
waterfall.js
/**
* Created by Capricorncd.
* Date: 2018/12/14 16:00
* https://github.com/capricorncd
*/
import App from './app.js'
// 默认配置文件
const DEFAULT_OPTS = {
// 外容器
wrapper: null,
// 子元素选择器
itemSelector: '',
// 元素间距
gutter: 20,
itemWidth: 300
}
class ZxWaterfall {
constructor (opts) {
this.opts = Object.assign({
}, DEFAULT_OPTS, opts)
// 数据列表
this.list = []
this.init()
// 监听window.onresize
App.addEvent(window, 'resize', this.resetPosition.bind(this))
}
init () {
let opts = this.opts
if (!App.isElement(opts.wrapper)) {
throw new Error(`瀑布流外容器非DOM元素`)
}
// 获取容器Rect信息
let wrapperBox = opts.wrapper.getBoundingClientRect()
// console.log(wrapperBox.width)
// 可列数
let columnNum = Math.floor(wrapperBox.width / (opts.itemWidth + opts.gutter))
// 元素实际宽度
this.itemWidth = (wrapperBox.width - (columnNum + 1) * opts.gutter) / columnNum
// 列数组
this.columns = Array