瀑布流

<!DOCTYPE html>

<html>

 

<head>

<meta charset="UTF-8">

<title></title>

<style type="text/css">

* {

padding: 0;

margin: 0;

}

#list {

list-style: none;

position: relative;

min-width: 150px;

}

 

#list li {

position: absolute;

width: 140px;

margin-left: 10px;

margin-top: 10px;

background: #CCCCCC;

transition: all 0.5s;

}

</style>

</head>

 

<body>

<ul id="list">

 

</ul>

</body>

 

</html>

<script type="text/javascript">

function game() {

var list = document.getElementById("list");

 

// 定义 li 的宽度,变量名大写用来表示常量

var LIWIDTH = 150;

 

function randHeight(min, max) {

return parseInt(Math.random() * (max - min + 1) + min);

}

// 定义存储 li 的数组

var existLiArr = [];

// 这个 bol  为 true 的时候,代表创建新的 li,为 false 的时候代表使用已经存在的 li

function createLI(bol) {

// 计算多少列

var COLS = parseInt(document.body.clientWidth / LIWIDTH);

 

//  采用数组记录每一“列”的高度

var colHeightArr = [];

// 创建 li之前,每一列的高度都为0

for(var i = 0; i < COLS; i++) {

colHeightArr[i] = 0;

}

 

function findMinCol() {

var min = colHeightArr[0];

var minIndex = 0;

for(var i = 0; i < colHeightArr.length; i++) {

if(min > colHeightArr[i]) {

min = colHeightArr[i];

minIndex = i;

}

}

return minIndex;

}

 

// 创建50个 li

for(var i = 0; i < 50; i++) {

var aLi = existLiArr[i] || document.createElement("li");

if (bol == true) {

var height = randHeight(50, 200);

aLi.style.height = height + "px";

}

 

 

// 找到最短的那一列(minLi是下标)

var minLi = findMinCol();

// 计算 aLi 的 left

aLi.style.left = minLi * LIWIDTH + "px";

aLi.style.top = colHeightArr[minLi] + "px";

aLi.innerHTML = i + 1;

if (bol == true) {

// 把 aLi 放到 list 里面

list.appendChild(aLi);

// 把 li 保存到数组里面

existLiArr.push(aLi);

colHeightArr[minLi] += (height + 10);

}else{

colHeightArr[minLi] += (aLi.offsetHeight  +10);

}

 

 

}

}

createLI(true);

 

// 窗口大小的检测

window.onresize = function() {

// list.innerHTML = "";

createLI(false);

}

 

}

game();

</script>

原文地址:https://www.cnblogs.com/gutianda/p/6027925.html