html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>瀑布流案列</title>
<link rel="stylesheet" href="css/通用符.css">
<script src="js/beixiAjax.js"></script>
<style>
.out{
position: relative;
margin: 0 auto;
}
.in{float: left;}
img{
margin: 10px;
padding: 10px;
border: 1px solid lightgray;
border-radius: 15px;
box-shadow: 0px 0px 5px orange;
}
</style>
</head>
<body>
<div class="out">
</div>
<script>
window.onload=function(){
window.beixiAjax({
type:'get',
url:'瀑布流案列.php',
success:function(res){
//准备页面元素
var dataarr=res;
var outDiv=document.querySelector('.out');
for(var i=0;i<dataarr.length;i++){
var div=document.createElement('div');
div.className='in';
div.innerHTML='<img src="'+dataarr[i]+'">';
outDiv.appendChild(div);
}
//构建瀑布流
var inDiv=document.querySelectorAll('.in');
var num=Math.floor(document.documentElement.clientWidth/inDiv[0].offsetWidth);
// console.log(document.documentElement.clientWidth);
// console.log(inDiv[0].offsetWidth);
// console.log(num);
outDiv.style.width=num*inDiv[0].offsetWidth+'px';
var heightarr=[];
for(var i=0;i<inDiv.length;i++){
if(i<num){
//表示第一行
heightarr.push(inDiv[i].offsetHeight);
}else{
//其余行
inDiv[i].style.position='absolute';
minheight=Math.min.apply(null,heightarr);
minindex=heightarr.indexOf(minheight);
//开启定位
inDiv[i].style.top=minheight+'px';
inDiv[i].style.left=inDiv[minindex].offsetLeft+'px';
//将数组中高度累加
heightarr[minindex]+=inDiv[i].offsetHeight;
}
}
}
})
}
</script>
</body>
</html>
php
<?php
$dataarr=['img/i1.jpg','img/i2.jpg','img/i3.jpg','img/i4.jpg','img/i5.jpg','img/i6.jpg','img/i7.jpg',
'img/i8.jpg','img/i9.jpg','img/i10.jpg','img/i11.jpg','img/i12.jpg','img/i13.jpg','img/i14.jpg','img/i15.jpg'];
echo json_encode($dataarr);
?>
老师,是我的代码有错吗?为什么排版还是有问题?求解:
效果图:
