当前位置:首页 > JavaScript

js实现瀑布流

2026-01-13 14:24:18JavaScript

实现瀑布流布局

瀑布流布局是一种常见的网页布局方式,常用于图片展示、商品列表等场景。以下是使用 JavaScript 实现瀑布流布局的几种方法。

纯 JavaScript 实现

通过计算元素的位置和高度动态排列元素。

function waterfall(container, box, columnCount) {
  const containerEl = document.querySelector(container);
  const boxEls = document.querySelectorAll(box);
  const containerWidth = containerEl.offsetWidth;
  const boxWidth = boxEls[0].offsetWidth;
  const gap = (containerWidth - boxWidth * columnCount) / (columnCount - 1);

  const heightArr = [];
  boxEls.forEach((el, index) => {
    if (index < columnCount) {
      el.style.position = 'absolute';
      el.style.left = index * (boxWidth + gap) + 'px';
      el.style.top = '0';
      heightArr.push(el.offsetHeight);
    } else {
      const minHeight = Math.min(...heightArr);
      const minIndex = heightArr.indexOf(minHeight);
      el.style.position = 'absolute';
      el.style.left = minIndex * (boxWidth + gap) + 'px';
      el.style.top = minHeight + gap + 'px';
      heightArr[minIndex] = minHeight + gap + el.offsetHeight;
    }
  });
}

window.onload = function() {
  waterfall('.container', '.box', 3);
};

使用 CSS Grid 和 JavaScript 结合

CSS Grid 提供更灵活的布局方式,结合 JavaScript 动态计算高度。

js实现瀑布流

function waterfallGrid(container, box) {
  const containerEl = document.querySelector(container);
  const boxEls = document.querySelectorAll(box);
  const columnCount = 3;
  containerEl.style.display = 'grid';
  containerEl.style.gridTemplateColumns = `repeat(${columnCount}, 1fr)`;
  containerEl.style.gridGap = '10px';

  boxEls.forEach(el => {
    el.style.marginBottom = '10px';
  });
}

使用 Flexbox 和 JavaScript 结合

Flexbox 可以简化布局逻辑,但需要额外处理高度。

function waterfallFlex(container, box) {
  const containerEl = document.querySelector(container);
  const boxEls = document.querySelectorAll(box);
  containerEl.style.display = 'flex';
  containerEl.style.flexWrap = 'wrap';
  containerEl.style.justifyContent = 'space-between';

  boxEls.forEach(el => {
    el.style.width = '30%';
    el.style.marginBottom = '20px';
  });
}

使用现成的库(如 Masonry)

Masonry 是一个流行的瀑布流布局库,简化了实现过程。

js实现瀑布流

// 引入 Masonry 库后使用
const masonry = new Masonry('.container', {
  itemSelector: '.box',
  columnWidth: 200,
  gutter: 10
});

响应式瀑布流布局

通过监听窗口大小变化动态调整布局。

function responsiveWaterfall() {
  const width = window.innerWidth;
  const columnCount = width < 768 ? 2 : width < 1024 ? 3 : 4;
  waterfall('.container', '.box', columnCount);
}

window.addEventListener('resize', responsiveWaterfall);
window.addEventListener('load', responsiveWaterfall);

动态加载内容

结合 AJAX 或 Fetch API 动态加载内容并更新瀑布流。

function loadMoreContent() {
  fetch('api/content')
    .then(response => response.json())
    .then(data => {
      const container = document.querySelector('.container');
      data.forEach(item => {
        const box = document.createElement('div');
        box.className = 'box';
        box.innerHTML = `<img src="${item.image}" alt="${item.title}">`;
        container.appendChild(box);
      });
      waterfall('.container', '.box', 3);
    });
}

以上方法可以根据实际需求选择适合的实现方式。纯 JavaScript 实现灵活性高,但代码量较大;使用 CSS Grid 或 Flexbox 简化了布局逻辑;现成的库如 Masonry 提供了更多功能和优化。

标签: 瀑布js
分享给朋友:

相关文章

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js实现选题

js实现选题

实现选题功能的JavaScript方法 基础实现方案 使用数组存储选项,通过随机索引选取: const options = ['选项A', '选项B', '选项C', '选项D']; const r…

js实现目录

js实现目录

实现目录的基本思路 在JavaScript中实现目录功能通常涉及以下几个核心步骤:解析文档中的标题元素(如h1-h6),动态生成目录结构,并添加交互逻辑(如点击跳转)。以下是具体实现方法: 解析标题…

js钟表实现

js钟表实现

实现JavaScript钟表的基本方法 创建一个简单的JavaScript钟表可以通过以下步骤完成,涵盖数字和模拟两种形式。 数字钟表实现 HTML结构只需一个显示时间的容器: <div i…

链表实现js

链表实现js

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和一个指向下一个节点的指针(单向链表)或两个指针(双向链表)。与数组不同,链表在内存中非连续存储,插入和删除操作更高效,但随机…

js实现交换

js实现交换

交换变量的方法 在JavaScript中,交换两个变量的值有多种方法。以下是常见的几种实现方式: 使用临时变量 通过引入一个临时变量来存储其中一个变量的值,实现交换: let a = 1; le…