JS实现瀑布流布局

瀑布流布局是一种常见的网页布局方式,可以实现页面内容的动态排列,使页面看起来更加美观。下面是一个简单的JS实现瀑布流布局的示例:

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>瀑布流布局</title>
<style>
    .waterfall {
        column-count: 4;
        column-gap: 10px;
    }

    .item {
        margin-bottom: 10px;
    }
</style>
</head>
<body>
<div class="waterfall" id="waterfall">
</div>

<script>
    const waterfall = document.getElementById('waterfall');

    const data = [
        'https://via.placeholder.com/150',
        'https://via.placeholder.com/200',
        'https://via.placeholder.com/250',
        'https://via.placeholder.com/300',
        'https://via.placeholder.com/350',
        'https://via.placeholder.com/400',
        'https://via.placeholder.com/450',
        'https://via.placeholder.com/500',
    ];

    data.forEach((url) => {
        const item = document.createElement('div');
        item.className = 'item';
        const img = document.createElement('img');
        img.src = url;
        item.appendChild(img);
        waterfall.appendChild(item);
    });
</script>
</body>
</html>

在这个示例中,我们首先定义了一个包含图片链接的数组data,然后使用forEach方法遍历数组,创建div元素作为每个图片的容器,并设置其样式为item。然后创建img元素,设置其src属性为对应的图片链接,最后将img元素添加到div容器中,并将整个div容器添加到waterfall容器中。

通过这种方式,我们可以实现一个简单的瀑布流布局,使页面内容以多列的方式动态排列。你可以根据实际需求调整列数和间距等样式来实现不同的效果。

相关推荐
掘根2 分钟前
【Qt】绘图
开发语言·qt
咖啡续命又一天22 分钟前
python 自动化采集 ChromeDriver 安装
开发语言·python·自动化
FuckPatience36 分钟前
Vue ASP.Net Core WebApi 前后端传参
前端·javascript·vue.js
huohaiyu1 小时前
synchronized (Java)
java·开发语言·安全·synchronized
一枚前端小能手1 小时前
🔥 SSR服务端渲染实战技巧 - 从零到一构建高性能全栈应用
前端·javascript
Komorebi_99991 小时前
Vue3 provide/inject 详细组件关系说明
前端·javascript·vue.js
_OP_CHEN1 小时前
C++基础:(九)string类的使用与模拟实现
开发语言·c++·stl·string·string类·c++容器·stl模拟实现
蓝天智能1 小时前
QT MVC中View的特点及使用注意事项
开发语言·qt·mvc
不一样的少年_1 小时前
【前端效率工具】:告别右键另存,不到 50 行代码一键批量下载网页图片
前端·javascript·浏览器
Asort1 小时前
JavaScript设计模式(八):组合模式(Composite)——构建灵活可扩展的树形对象结构
前端·javascript·设计模式