当前位置:首页 > 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 动态计算高度。

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 是一个流行的瀑布流布局库,简化了实现过程。

// 引入 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 实现vue

js 实现vue

实现 Vue 的核心功能 在 JavaScript 中实现 Vue 的核心功能需要模拟数据绑定、虚拟 DOM 和响应式系统。以下是一个简化版的实现思路: 响应式系统 通过 Object.define…

js实现

js实现

JavaScript 实现方法 JavaScript 是一种广泛使用的编程语言,适用于网页开发、服务器端编程以及移动应用开发。以下是几种常见的 JavaScript 实现方法: 网页交互功能 使用…

js实现轮播

js实现轮播

实现基础轮播效果 使用HTML结构创建轮播容器和图片元素: <div class="carousel"> <div class="carousel-inner">…

js实现分页

js实现分页

实现分页的基本思路 分页功能通常需要处理数据分割、页码生成和用户交互。核心逻辑包括计算总页数、根据当前页截取数据、渲染页码按钮等。 前端分页实现(静态数据) 假设已有全部数据,仅需前端分页展示:…

js实现验证码

js实现验证码

实现验证码的JavaScript方法 生成随机验证码 使用Math.random()生成随机字符串,结合数字和字母: function generateCaptcha() { const cha…

vue实现js休眠

vue实现js休眠

Vue 中实现 JavaScript 休眠 在 Vue 中实现 JavaScript 休眠通常需要使用异步方式,以避免阻塞主线程。以下是几种常见方法: 使用 setTimeout 和 Promis…