站长资源网络编程

js自定义瀑布流布局插件

整理:jimmy2026/8/1浏览2
简介瀑布流布局是网页中经常采用的一种布局方式,其布局有如下特点:瀑布流布局特点: (1)图文元素按列排放 (2)列宽一致,但高度不等 (3)布局过程中将优先向高度最小的列补充数据以下是自定义的一个jQuery瀑布流插件:jquery.myWaterfull.js(function ($) ); arrHeight.push($(item).height() + space); //将第一行中的列的高度添加到数组中 } else { //找寻列高最小的那一列 var minIndex = 0; var minValue = arrHeight[minIndex]; //循环遍历找出最小的列高值 for (var i = 0; i < arrHeight.length; i++) { if (minValue > arrHeight[i]) { minValue = arrHeight[i]; minIndex = i; } } //对余下的子元素挨个排列布局 $(item).css({ top: minValue + space, left: minIndex * (childWidth + space) }); //更新最小列高 arrHeight[minIndex] += $(item).height() + space; } }); //由于这里是利用定位对子元素进行布局,所以要更新父元素的高度 //当然也可以利用浮动对子元素进行布局 var maxHeight = 0; for (var i = 0; i < arrHeight.length; i++) { if (maxHeight < arrHeight[i]) { maxHeight = arrHeight[i]; } } //设置父元素的高度 $(this).height(maxHeight); } }); })(jQuery);

使用示例:

这里假设一个HTML结构:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
 <meta charset="UTF-8">
 <title>瀑布流案例原始</title>
 <style>
* {
 margin: 0;
 padding: 0;
}

body {
 font-family: Microsoft Yahei;
 background-color: #f5f5f5;
}

.container {
 width: 1200px;
 margin: 0 auto;
 padding-top: 50px;
}

.container > .items {
 position: relative;
}

.container > .items > .item {
 width: 232px;
 position: absolute;
 box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
 overflow: hidden;
}

.container > .items > .item > img {
 width: 100%;
 display: block;
 height: 232px;
}

.container > .items > .item:nth-child(3n) > img {
 width: 100%;
 display: block;
 height: 350px;
}

.container > .items > .item > p {
 margin: 0;
 padding: 10px;
 background: #fff;
}

.container > .btn {
 width: 280px;
 height: 40px;
 text-align: center;
 line-height: 40px;
 background-color: #ccc;
 border-radius: 8px;
 font-size: 24px;
 cursor: pointer;
}

.container > .loading {
 background-color: transparent;
}
</style>
</head>
<body>
<div class="container">
 <div class="items">

 </div>
 <div class="btn loading">正在加载...</div>
</div>

书写脚本文件,这里假设从后台获取子元素的数据,并用artTemplate模板引擎将数据渲染到页面:

<script src="/UploadFiles/2021-04-02/jquery.min.js">

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:Bootstrap fileinput文件上传预览插件使用详解

下一篇:简单实现js点击展开二级菜单功能