百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 文章教程 > 正文

前端【瀑布流布局】多种解决方案集锦

xsobi 2025-04-07 20:37 6 浏览

在如今的移动互联网时代,H5类商城产品已经成为了各大电商平台的标配。而在这些H5商城产品中,瀑布流布局已经成为了很多商城产品的首选。瀑布流布局不仅美观大方,而且可以更好地展示商品,提高用户的购买欲望。

在实现瀑布流布局的过程中,我们需要选择一些技术,来帮助我们完成这个任务。下面是我们选择的技术:


1、纯CSS方式:

multi-columns 是CSS3中提供的一个多列布局模块,用于将一个元素的内容分成多列进行显示,可以避免单独使用 position 或者 float 造成的布局问题,并且可以自动调整列的宽度以适应不同大小的屏幕。

此种方式只适合固定数据展示,也就是说对于动态添加不是很合适,当然也不绝对的,还需要看具体代码实现。

CSS

Bash
em {
    color: #ff0000;
}

#list-container {
    width: 375px;
    margin: 0 auto;
    /* 指定瀑布流列数 */
    column-count: 2;
   /* 瀑布流列之间的间隙 */
    column-gap: 1rem;
}

.thumbnail {
  margin:1rem 0;
}

.thumbnail>img {
    width: 100%;
}

HTML

Bash

  
  
  

Javascript

(()=>{

    // 商品展示模板
    const template = document.getElementById('template').innerHTML;

    //获取单个产品数据 demo
    const getProduct = function(index){

        // 随机一个高度,范围:100至150。
        const height = 100 + Math.floor(Math.random() * 50);
        return {
            "id": index,
            "title": '商品' + (index),
            "description": 'H5商城产品中,瀑布流布局已经成为了很多商城产品的首选。',
            "price": height,

            // 随机生成一个图片 demo
            "img": "https://picsum.photos/150/" + (height),
            "imgHeight": height
        };
    }

    // 获取产品预览标签(简单的模板替换)
    const getProductTag = function(product){
        return template.replace(/{{\w+}}/g, str => {
            str = str.replace(/[{}]+/g,'');
            return product[str];
        });
    }

    // 填充一个产品到瀑布流
    const fillWaterfall = function(product){
		    // 填充瀑布流
		    document.getElementById('list-container').innerHTML += getProductTag(product);
    }

    // 测试用例
    let count = 0;
    setInterval(function(){
        count++;
		    if(count>50) return;
        const product = getProduct(count);
        fillWaterfall(product)
    },1000)

})()

因为排序方式的不同,所以只适合固定数据的瀑布流布局。

因为我们期望的是左1个、右1个。

2、flexbox布局:

瀑布流列数不在css中指定,可以HTML中随意增加列数。

CSS

em {
    color: #ff0000;
}

#list-container {
    width: 375px;
    margin: 0 auto;
    display: flex;
}

#list-container>.list-item {
  flex: 1;
}

.thumbnail {
  margin:1rem 0.5rem;
}

.thumbnail>img {
    width: 100%;
}

HTML

Javascript

(()=>{

    // 商品展示模板
    const template = document.getElementById('template').innerHTML;

    //获取单个产品数据 demo
    const getProduct = function(index){

        // 随机一个高度,范围:100至150。
        const height = 100 + Math.floor(Math.random() * 50);
        return {
            "id": index,
            "title": '商品' + (index),
            "description": 'H5商城产品中,瀑布流布局已经成为了很多商城产品的首选。',
            "price": height,

            // 随机生成一个图片 demo
            "img": "https://picsum.photos/150/" + (height),
            "imgHeight": height
        };
    }

    // 获取产品预览标签
    const getProductTag = function(product){
        return template.replace(/{{\w+}}/g, str => {
            str = str.replace(/[{}]+/g,'');
            return product[str];
        });
    }

    // 瀑布流所有列
    const waterfalls = document.getElementsByClassName('list-item');

    // 填充一个产品到瀑布流
    const fillWaterfall = function(product){
        /**
         * 计算下一个产品应该填充到哪里
         */
        let minIndex = 0;
        let minHeight = -1;
        Array.from(waterfalls).forEach((element, index) => {
            const height = element.children[0].offsetHeight;
            minHeight == -1 && (minHeight = height)
            if(minHeight > height){
                minHeight = height;
                minIndex = index;
            }
        });

        // 填充瀑布流
        waterfalls[minIndex].children[0].innerHTML += getProductTag(product);
    }


})()


3、position方式

此种方式太复杂,需要各种计算。但是这种方式相对灵活,同时需要更多的编程工作。

以下是一个简单的例子:

css

em {
    color: #ff0000;
}

#list-container {
    width: 375px;
    margin: 0 auto;
    position: relative;
}

#list-container>.list-item {
    position: absolute;
}

.thumbnail>img {
    width: 100%;
}

HTML

Javascript

(()=>{

    // 商品展示模板
    const template = document.getElementById('template').innerHTML;

    //获取单个产品数据 demo
    const getProduct = function(index){

        // 随机一个高度,范围:100至150。
        const height = 100 + Math.floor(Math.random() * 50);
        return {
            "id": index,
            "title": '商品' + (index),
            "description": 'H5商城产品中,瀑布流布局已经成为了很多商城产品的首选。',
            "price": height,

            // 随机生成一个图片 demo
            "img": "https://picsum.photos/150/" + (height),
            "imgHeight": height
        };
    }

    // 获取产品预览标签
    const getProductTag = function(product){
        return template.replace(/{{\w+}}/g, str => {
            str = str.replace(/[{}]+/g,'');
            return product[str];
        });
    }

    const columnInfo = {
      // 列数
      count: 2,
    };

    // 记录每列当前总高度
    const keys = [];
    new Array(2).fill('1').forEach((item, index)=>{
      keys.push(index);
      columnInfo[index] = 0;
    });


    // 填充一个产品到瀑布流
    const fillWaterfall = function(product){
       /**
         * 计算下一个产品应该填充到哪里
         */
        let minIndex = 0;
        let minHeight = -1;
        keys.forEach((key, index)=>{
            const height = columnInfo[index];
            minHeight == -1 && (minHeight = height)
            if(minHeight > height){
                minHeight = height;
                minIndex = index;
            }
        });

				// 填充瀑布流
        document.getElementById('list-container').innerHTML += getProductTag(product);

				// 设置新增项的宽度以及位置
        const lastElementNode = document.getElementById('list-container').lastElementChild;
        lastElementNode.style.width = 375 / 2 - 6;
        lastElementNode.style.left = (minIndex * 375 / 2 + 6) + 'px';
        lastElementNode.style.top = (columnInfo[minIndex]) + 'px';
        //  累加列高度
        columnInfo[minIndex] += lastElementNode.offsetHeight -10;

    }


})()


4、滑动加载

滑动加载的插件比较多,您可以线下试试,增加滑动加载的代码。

一个简单的示例:

window.addEventListener('scroll', function() {
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        var windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
        if (scrollTop + windowHeight >= scrollHeight - 100) {
            count++;
            fillWaterfall(getProduct(count))
            count++;
            fillWaterfall(getProduct(count))
        }
    });

希望本文能够对您有所帮助,感谢您的阅读!

人人为我,我为人人,谢谢您的浏览,我们一起加油吧。

相关推荐

Python入门之Python的数据类型和常用操作符

一、Python的数据类型1、在Python中,int表示整型,bool表示布尔类型,float表示浮点类型,str表示字符串。计算机只认识二进制数,所有的编程语言都会转换成二进制语言给CPU按一定的...

金风科技:拟转让澳洲Moorabool风电项目股权及授出26%股权期权

【金风科技:拟转让澳洲Moorabool风电项目股权及授出26%股权期权】财联社12月20日电,金风科技公告,公司全资子公司金风国际Moorabool以1.77亿澳元的价格向Nebras电力转让其持有...

西门子SCL语言编程——PEEK/POKE指令

在SCL语言编程的时候,有两个特别有意思的指令,即读取存储地址和写入存储地址指令,梯形图中貌似没有的。标准地说是两类而不是两个,因为读和写都不止一个指令。先了解这两类指令的基本说明和用法,本篇后面的示...

【 PLC知识分享】PLC中常说的位元件、字元件的区别

#头条创作挑战赛#...

西门子TIA博途S7-1200/1500学习7间接寻址指令PEEK的使用

描述:...

C语言 | 关键字asm 、auto、bool、break 解析

asm插入一个汇编指令....

一文带你了解PLC的基本数据类型,很多电气师傅都不知道

...

什么是Python 之 ? 16 布尔值bool

Python的布尔值类型bool明确的一点是boolean值不是python专有的,其他编程语言javajavascriptphp等其实都有...

自动化PLC 基础 一个变量变成32个Bool 量 #plc编程

自动化PLCDINT数据类型变为BOOL量用。一次定义32个布尔量(BOOL)。前面给大家分享了罗可韦尔ABPLC数据类型的时候有讲到对于整数在ABPLC中最好定义为DINT的数据类型。今天给大家分享...

python数据类型-布尔类型bool(python中的布尔类型提供了哪两个值)

布尔类型是用于表示一种是与不是,对于不对等关系的类型布尔值只有两个:True和False布尔类型一般用于if判断和while循环中...

Python的布尔类型(bool)和布尔表达式

1.布尔类型(bool)Python的布尔类型是bool,表示真(True)或假(False)。它是整数的子类,True对应1,False对应0,但它们主要用于逻辑判断。值:True:代表...

记oracle日志挖掘实操&查询归档不正常增长情况(一)

问题:最近几周经常手动删除归档日志,归档日志报空间不足(预留800G空间已用完),基于此查询归档日志情况(近期业务有所上涨)。-----------------------------此为回溯操作流程...

每天自动备份Oracle数据库(定时备份oracle数据库)

本文以CentOS7.6系统与Oracle11g为例,教你如何在Linux下设置每天自动备份Oracle数据库。一.先找到数据库的环境变量如果是在root账户下,须先登录到数据库所在账户suor...

避坑指南:KingbaseES Oracle模式中隐藏的"双Date"玄机

在数据库开发中,日期时间处理是高频操作场景。当您从Oracle迁移到国产数据库时,是否遇到过这样的困惑:...

ORACLE常见问题-100问(系列二)(oracle报错大全)

100.sql>startuppfile和ifile,spfile有什么区别?pfile就是Oracle传统的初始化参数文件,文本格式的;...