原生js 实现瀑布流布局
原理:
- 设置图片宽度一致
- 根据父元素的宽度和图片宽度,计算出列数和间距
- 当图片加载完成,所有图片依次放置在高度最小的列数下面
代码示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>waterfall</title>
<link rel="stylesheet" href="">
<style type="text/css" media="screen">
* {
margin: 0;
padding: 0;
}
.itemBox {
width: 1050px;
margin: 0 auto;
position: relative;
}
.item {
border: 1px solid #ccc;
padding: 4px;
position: absolute;
}
.item img{
position: relative;
}
</style>
</head>
<body>
<div class="itemBox">
<div class="item">
<img src="./images/P_000.jpg" alt="">
</div>
<div class="item">
<img src="./images/P_001.jpg" alt="">
</div>
<div class="item">
<img src="./images/P_002.jpg" alt="">
</div>
<div class="item">
<img src="./images/P_003.jpg" alt="">
</div>
<div class="item">
<img src="./images/P_004.jpg" alt="">
</div>
<div class="item">
<img src="./images/P_005.jpg" alt="">
</div>
<div class="item">
<img src="./images/P_006.jpg" alt="">
</div>
<div class="item">
<img src="./images/P_007.jpg" alt="">
</div>
<div class="item">
<img src="./images/P_008.jpg" alt="">
</div>
<div class="item">
<img src="./images/P_009.jpg" alt="">
</div>
</div>
<script type="text/javascript">
window.onload = function(){
var itemBox = document.querySelector('.itemBox');
var items = document.getElementsByClassName('item');
var itemBoxW = itemBox.offsetWidth;
var itemW = items[0].offsetWidth;
var column = parseInt(itemBoxW / itemW);
var distence = (itemBoxW - itemW * column) / (column - 1);
var arr = [];
waterFull()
function waterFull(){
for(var i =0; i < items.length; i++){
if(i < column){
items[i].style.left = itemW * i + i * distence + 'px'
arr[i] = items[i].offsetHeight;
}else{
let mObj = getMin(arr);
items[i].style.top = mObj.min + distence + 'px'
items[i].style.left = itemW * mObj.mIndex + mObj.mIndex * distence + 'px'
arr[mObj.mIndex] = arr[mObj.mIndex] + items[i].offsetHeight + distence;
}
}
}
function getMin(arr){
let min = arr[0];
let mIndex = 0;
for(var i =1; i<arr.length; i++){
if(arr[i] < min){
min = arr[i]
mIndex = i
}
}
return {min:min, mIndex:mIndex}
}
window.onscroll = function(){
let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
let minHeight = getMin(arr).min;
if((scrollTop + window.innerHeight) > minHeight){
var json = [
{ "src": "./images/P_000.jpg" },
{ "src": "./images/P_001.jpg" },
{ "src": "./images/P_002.jpg" },
{ "src": "./images/P_003.jpg" },
{ "src": "./images/P_004.jpg" },
{ "src": "./images/P_005.jpg" },
{ "src": "./images/P_006.jpg" },
{ "src": "./images/P_007.jpg" },
{ "src": "./images/P_008.jpg" },
{ "src": "./images/P_009.jpg" },
{ "src": "./images/P_010.jpg" }
];
for(var i =0; i< json.length;i++){
let div = document.createElement('div');
div.className = 'item';
let img = document.createElement('img')
img.src = json[i].src;
div.appendChild(img)
itemBox.appendChild(div);
}
waterFull()
}
}
}
</script>
</body>
</html>