原生js实现瀑布流
js实现
代码思路
此博客
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.outer{
width: 100%;
position: relative;
}
.outer div{
width: 300px;
background-color: bisque;
position: absolute;
}
.outer div:nth-child(1){
height: 150px;
}
.outer div:nth-child(2){
height: 100px;
}
.outer div:nth-child(3){
height: 370px;
}
.outer div:nth-child(4){
height: 588px;
}
.outer div:nth-child(5){
height: 690px;
}
.outer div:nth-child(6){
height: 163px;
}
.outer div:nth-child(7){
height: 345px;
}
.outer div:nth-child(8){
height: 237px;
}
.outer div:nth-child(9){
height: 171px;
}
.outer div:nth-child(10){
height: 360px;
}
.outer div:nth-child(11){
height: 435px;
}
.outer div:nth-child(12){
height: 135px;
}
</style>
</head>
<body>
<div class="outer">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
<div>15</div>
<div>16</div>
</div>
<script>
// 获取子元素
let outerChildren = document.getElementsByClassName('outer')[0].children
// 方法
function waterFall () {
// 获取子元素的宽度,并与margin值相加
let childrenWidth = 310
// 获取总宽度
let bodyWidth = document.body.clientWidth
// 设置总列数
let col = Math.floor(bodyWidth/childrenWidth)
let heightArr = []
let minIndex
let minHeight
outerChildren = Array.from(outerChildren)
outerChildren.forEach((item, index)=>{
let num = parseInt(getComputedStyle(item,null).height)
// 先排列第一行
if (index <= col) {
heightArr.push(num)
item.style.left = (index * childrenWidth) + 'px'
if(num < minHeight || !minHeight){
minHeight = num
minIndex = index
}
}
// 第二行
if (index > col) {
// 定位并添加一个新内容
item.style.top = (minHeight + 10) + 'px'
item.style.left = ((minIndex % col) * childrenWidth) + 'px'
// 并在最小高度后追加一个值
heightArr[minIndex] += (num + 10)
// 重新寻找最小高度
heightArr.forEach((item, index)=>{
if(item<heightArr[minIndex]){
minHeight = item
minIndex = index
}
})
}
})
}
waterFall()
</script>
</body>
</html>
CSS实现
在 css3 中提供了一种更方便的方式来实现瀑布流布局,及 multi-column 属性,大家可以自行查找,此处不再演示。

浙公网安备 33010602011771号