二.瀑布流
案例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box{
width: 800px;
border: 1px solid brown;
border-left: none;
border-right: none;
margin: auto;
}
.clumb{
width: 160px;
/*background: red;*/
float: left;
}
</style>
</head>
<body>
<input type="button" id="btn" value="添加图片" />
<div id="box">
<div class="clumb">
</div>
<div class="clumb"></div>
<div class="clumb"></div>
<div class="clumb"></div>
<div class="clumb"></div>
</div>
</body>
</html>
<script src="../../promiseAjax.js"></script>
<script type="text/javascript">
var btn = document.getElementById("btn");
var clumb = document.getElementsByClassName("clumb");
btn.onclick = function(){
var pro = promiseAjax({
method : "get",
url : "index.json"
});
pro.then(function(res){
var json = JSON.parse(res);
//console.log(json);
//var index = 0;
for (var i = 0; i < json.length; i++) {
//创建图片标签
var img = document.createElement("img");
img.src = json[i].src;
img.width = 160;//不加style,就不用加px;加了style,就要加px单位。
img.className = i;
img.height = json[i].height;
//clumb[index].appendChild(img);
//index++;
/*if(index == 5){
index = 0;
}*/
//1.添加前五张图片到clumb序列中
if(i < 5){
clumb[i].appendChild(img);
}else{
//2.计算得到最短的这一列clumb,
var index = getMinHeightIndex();
//3.每一次添加,会把图片追加到最短的这一列下面。
clumb[index].appendChild(img);
}
}
})
}
//计算当前调试最短的列的下标
function getMinHeightIndex(){
var minHeightIndex = 0;
var minHeightEle = clumb[0].offsetHeight;
for (var i = 0; i < clumb.length; i++) {
if(minHeightEle > clumb[i].offsetHeight){
minHeightEle = clumb[i].offsetHeight;
minHeightIndex = i;
}
}
return minHeightIndex;
}
//4当滚动条滚动到最短的这一列出现留白的时间,图片就开始以瀑布流的方式重新 加载。
window.onscroll = function(){
//什么情况算留白呢?
//滚动条滚走的距离
var stop = document.documentElement.scrollTop || document.body.scrollTop;
var t = document.documentElement.clientHeight + stop;
//获取最短的列
var index = getMinHeightIndex();
var h = clumb[index].offsetHeight;
if( t > h ){
btn.onclick();
}
}
</script>