html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src=".././../jquery.min.js"></script>
<script src="./index.js"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
list-style: none;
}
.content {
width: 1200px;
margin: 0 auto;
}
.content ul {
position: relative;
}
.content ul li {
width: 220px;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="content">
<ul>
<li style="background-color: rgba(red, green, blue, alpha);"></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<script>
// 生成数据
let dataArr = []
function randomColor() {
return Math.floor(Math.random() * 256)
}
for (let i = 0; i < 100; i++) {
dataArr.push({
height: Math.floor(Math.random() * (450 - 200) + 200),
color: `rgba(${randomColor()},${randomColor()},${randomColor()},.8)`
})
}
</script>
<script>
$(function () {
$('ul').waterFall({ data: dataArr })
})
</script>
</body>
</html>
js文件:
; (function () {
$.fn.waterFall = function (option) {
// 初始化li
let str = ''
option.data.forEach((e, i) => {
str += `<li style="height:${e.height}px; background-color:${e.color};">${i + 1}</li>`
})
$(this).html(str)
// 获取li jq对象
let liList = $(this).children()
const domWid = $(liList[0]).width()// li的宽度
const interval = 10 // li的间隔
let heightArr = [] //空数组,用来存放每一列li的高度
// 遍历li
$.each(liList, function (i, e) {
// 第一排
if (i < 5) {
$(e).css({ left: i * (domWid + interval) })
heightArr.push(parseInt($(e).css('height')))
} else {
// 找出数组中高度最小的
let min = heightArr[0]
let minIndex = 0
for (let i = 0; i < heightArr.length; i++) {
if (heightArr[i] < min) {
min = heightArr[i]
minIndex = i
}
}
$(e).css({ left: minIndex * (domWid + interval), top: min + interval })
// 重置列表高度
heightArr[minIndex] += option.data[i].height + interval
}
})
}
})()