|
| 1 | +import { debounce } from "./help.js"; |
| 2 | +/** |
| 3 | + * 瀑布流 |
| 4 | + * @param {Object} options |
| 5 | + * @param {HTMLElement} options.$el 父容器 |
| 6 | + * @param {Number} options.count 列数 |
| 7 | + * @param {Number} options.gap 间距 |
| 8 | + * @param {Number} options.complete 列的宽度 |
| 9 | + */ |
| 10 | +export default class Waterfall { |
| 11 | + constructor(options) { |
| 12 | + this.$el = null; // 父容器 |
| 13 | + this.count = 4; // 列数 |
| 14 | + this.gap = 10; // 间距 |
| 15 | + Object.assign(this, options); |
| 16 | + this.width = 0; // 列的宽度 |
| 17 | + this.items = []; // 子元素集合 |
| 18 | + this.H = []; // 存储每列的高度方便计算 |
| 19 | + this.flag = null; // 虚拟节点集合 |
| 20 | + this.init(); |
| 21 | + } |
| 22 | + #resize() { |
| 23 | + debounce(() => { |
| 24 | + this.rerender(); |
| 25 | + }, 300).call(this); |
| 26 | + } |
| 27 | + |
| 28 | + init() { |
| 29 | + this.items = Array.from(this.$el.children); |
| 30 | + this.reset(); |
| 31 | + this.render(); |
| 32 | + window.addEventListener("resize", this.#resize.bind(this)); |
| 33 | + } |
| 34 | + |
| 35 | + reset() { |
| 36 | + this.flag = document.createDocumentFragment(); |
| 37 | + const containerWidth = this.$el.clientWidth - (this.count - 1) * this.gap; |
| 38 | + this.width = containerWidth / this.count; |
| 39 | + this.H = new Array(this.count).fill(0); |
| 40 | + this.$el.innerHTML = ""; |
| 41 | + } |
| 42 | + |
| 43 | + rerender() { |
| 44 | + this.items = Array.from(this.$el.children); |
| 45 | + this.reset(); |
| 46 | + this.render(); |
| 47 | + } |
| 48 | + |
| 49 | + render() { |
| 50 | + const { width, items, flag, H, gap } = this; |
| 51 | + items.forEach((item) => { |
| 52 | + item.style.width = width + "px"; |
| 53 | + item.style.position = "absolute"; |
| 54 | + let img = item.querySelector("img"); |
| 55 | + if (img.complete) { |
| 56 | + let tag = H.indexOf(Math.min(...H)); |
| 57 | + item.style.left = tag * (width + gap) + "px"; |
| 58 | + item.style.top = H[tag] + "px"; |
| 59 | + H[tag] += (img.height * width) / img.width + gap; |
| 60 | + flag.appendChild(item); |
| 61 | + } else { |
| 62 | + img.addEventListener("load", () => { |
| 63 | + let tag = H.indexOf(Math.min(...H)); |
| 64 | + item.style.left = tag * (width + gap) + "px"; |
| 65 | + item.style.top = H[tag] + "px"; |
| 66 | + H[tag] += (img.height * width) / img.width + gap; |
| 67 | + flag.appendChild(item); |
| 68 | + this.$el.append(flag); |
| 69 | + }); |
| 70 | + } |
| 71 | + }); |
| 72 | + this.$el.append(flag); |
| 73 | + } |
| 74 | +} |
0 commit comments