<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./jquery-3.6.0.min.js" type="text/javascript"></script>
<style>
body {
background-color: #eee;
}
* {
margin: 0;
padding: 0;
}
img {
border: none;
}
a {
text-decoration: none;
}
header {
width: 600px;
height: 20px;
margin: 20px auto;
text-align: center;
font-size: 30px;
font-weight: 700;
line-height: 20px;
}
.wrap {
width: auto;
height: auto;
position: relative;
margin: 0 auto;
}
.wrap .box {
float: left;
padding: 10px;
background-color: #fff;
margin: 10px;
border-radius: 20px;
}
.wrap .box:hover {
animation: aa 2s ease;
}
.wrap .box .info {
width: 300px;
height: auto;
border-radius: 8px;
}
.wrap .box .info img {
width: 100%;
border-radius: 10px;
}
.wrap .box .info>div {
width: 100%;
height: 40px;
line-height: 40px;
text-align: center;
}
.wrap .box .info>div>a {
color: #444;
}
@keyframes aa {
0% {opacity: 1;}
60% {opacity: 0.4;}
100% {opacity: 1;}
}
</style>
</head>
<body>
<header>瀑布流</header>
<div class="wrap">
<div class="box">
<div class="info">
<img src="./img/1.webp" alt=""/>
<div><a href="javascript:;">it is a title</a></div>
</div>
</div>
<div class="box">
<div class="info">
<img src="./img/2.webp" alt=""/>
<div><a href="javascript:;">it is a title</a></div>
</div>
</div>
<div class="box">
<div class="info">
<img src="./img/3.webp" alt=""/>
<div><a href="javascript:;">it is a title</a></div>
</div>
</div>
<div class="box">
<div class="info">
<img src="./img/4.webp" alt=""/>
<div><a href="javascript:;">it is a title</a></div>
</div>
</div>
<div class="box">
<div class="info">
<img src="./img/4.webp" alt=""/>
<div><a href="javascript:;">it is a title</a></div>
</div>
</div>
</div>
<script>
//图片排列
function place(){
//确定列数,在每一列图片最小高度的地方放入图片排列
const warp = document.querySelector('.wrap');
const boxs = document.querySelectorAll('.wrap .box');
var boxWidth = boxs[0].clientWidth;
var columns = Math.floor(window.innerWidth / boxWidth);
//分析高度最小
var minH = [];
for(let i=0; i<boxs.length; i++){
//dom已经排列好
if(i < columns){
minH[i] = boxs[i].clientHeight;
}else {
//一列排不完,放在高度最小的地方
var minh = Math.min.apply(null,minH);
var minIndex = getIndex(minh,minH);
console.log(minH,minh,minIndex);
//开始排列
placeBox(boxs[i],(minIndex * (boxWidth +20)),minH[minIndex]+20,i);
minH[minIndex] += boxs[i].clientHeight + 20;
}
}
}
function getIndex(minh,minH){
for(let index in minH){
if(minH[index] == minh){
return index;
}
}
}
var start = 0;
function placeBox(box,left,top,index){
if(start >= index) return;
box.style.position = 'absolute';
box.style.left = left + 'px';
box.style.top = top + 'px';
start = index;
}
place();
//高于window高度,更新dom
</script>
</body>
</html>
JS瀑布流
于 2022-02-19 09:20:58 首次发布