流式布局
什么叫流式布局
也称为瀑布流布局,是一种比较经典网页布局方法,特别是在常见于照片比较多的网页页面。普遍主要有两种流式布局方法。分别是
- 定宽不确定高
- 定高不确定宽
定宽不确定高
定高不确定宽
定宽不确定高-构思
- 动态生成 1000 个 li 标识,设定统一宽度 设置透明度 (具体设计中,只需获得 1000 个照片相对应的相对高度就可以)
- 打开计时器,每一行只开 3 个 li 标识 ,三个 li 标识,按正常次序先后放置就可以,后边的 li 标识转换逻辑性
- 每表明一个 li 标识,那就需要自身维持好一个二维数组 [第 1 列 li 标识相对高度结合,第 2 列 li 标识相对高度结合,第 3 列 li 标识相对高度结合]
- 统计分析出那一列 最少 和 相对应的字符(0,1,2)
- 把下一个 li 标识 放到相匹配下标底部位,与此同时算出字符相匹配列相对高度总数,设为 将要标注的 li 标签的 top
编码
<!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>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
li {
width: 33.33%;
border: 1px solid #000;
font-size: 30px;
text-align: center;
position: absolute;
top: 0;
left: 0;
list-style: none;
}
</style>
</head>
<body>
<ul></ul>
<script>
init();
function init() {
const ul = document.querySelector("ul");
for (let index = 0; index < 1000; index ) {
const li = document.createElement("li");
li.innerText = index;
li.style.backgroundColor = getRandomColor();
li.style.height =
Math.floor(Math.random() * (200 - 50 1) 50) "px";
li.style.opacity = "0";
ul.appendChild(li);
}
function getRandomColor() {
const color1 = Math.floor(Math.random() * 256);
const color2 = Math.floor(Math.random() * 256);
const color3 = Math.floor(Math.random() * 256);
return `rgb(${color1},${color2},${color3})`;
}
setWaterFall();
function setWaterFall() {
const lis = [...document.querySelectorAll("li")];
let index = 0;
const heightList = [[], [], []];
const timeId = setInterval(() => {
const li = lis.shift();
if (!li) {
clearInterval(timeId);
return;
}
if (index < 3) {
const left = index * li.clientWidth "px";
li.style.left = left;
heightList[index].push(li.clientHeight);
} else {
// 算出3个列分别代表高度 [1,2,3]
const sumHeightList = heightList.reduce(
(sumColumnHeight, columnList) => [
...sumColumnHeight,
columnList.reduce((a, b) => a b, 0),
],
[]
);
const { minIndex, minHeight } = getMinIndex(sumHeightList);
const left = minIndex * li.clientWidth "px";
const top = minHeight "px";
li.style.left = left;
li.style.top = top;
heightList[minIndex].push(li.clientHeight);
}
li.style.opacity = "1";
index ;
}, 500);
}
function getMinIndex(arr) {
let minIndex = 0;
let minHeight = arr[0];
for (let index = 0; index < arr.length; index ) {
const element = arr[index];
if (minHeight > element) {
minHeight = element;
minIndex = index;
}
}
return { minIndex, minHeight };
}
}
</script>
</body>
</html>
实际效果
文中已经参与「 . 」