index.html

<!DOCTYPE html>
<html>
<head>
<style>
.box {
width:70%;
position:relative;
}
.item {
position: absolute;
}
.item img{
width: 100%;
height:100%;
}
.loading{
width:100px;
height:100px;
margin:0 auto;
}
</style>
<title>2018301845周扬</title>
</head>
<body>
<script src="js/jquery-2.1.4.min.js"></script>
<div class="box" id="box">
<div id="loading" class="loading">
<script>
$box=$("#box");
$.ajax({
type:"GET",
url:"list.php",
dataType:"json",
beforeSend:function(){
$("#loading").html("<img src='img/loading.gif' style='width:80px'/>"); //在请求后台数据之前显示loading图标
},
success:function(result){
$box.empty();
data=result.data;
for(var i=0;i<data.length;i++){
$img='<div class="item">'+
'<img src="img/'+data[i].img+'">'+
'</div>'
$box.append($img)
}},
error:function(){
alert("查无此数据");
}
});
</script>
</body>
<script>
function waterFall() {
// 1 确定图片的宽度 - 滚动条宽度
var pageWidth = getClient().width-8;
var columns = 4; //列数
var itemWidth = parseInt(pageWidth/columns); //得到item的宽度
$(".item").width(itemWidth); //设置到item的宽度
var arr = [];
$(".box .item").each(function(i){
var height = $(this).find("img").height();
if (i < columns) {
// 2 第一行按序布局
$(this).css({
top:0,
left:(itemWidth) * i+20*i,
});
//将行高push到数组
arr.push(height);
} else {
// 其他行
// 3 找到数组中最小高度 和 它的索引
var minHeight = arr[0];
var index = 0;
for (var j = 0; j < arr.length; j++) {
if (minHeight > arr[j]) {
minHeight = arr[j];
index = j;
}
}
// 4 设置下一行的第一个盒子位置
// top值就是最小列的高度
$(this).css({
top:arr[index]+30,//设置30的距离
left:$(".box .item").eq(index).css("left")
});

// 5 修改最小列的高度
// 最小列的高度 = 当前自己的高度 + 拼接过来的高度
arr[index] = arr[index] + height+30;//设置30的距离
}
});
}
//clientWidth 处理兼容性
function getClient() {
return {
width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
}
}
// 页面尺寸改变时实时触发
window.onresize = function() {
//重新定义瀑布流
waterFall();
};
//初始化
window.onload = function(){
//实现瀑布流
waterFall();
}

</script>

</html>

连接数据库 fun.php

<?php 
header("Content-Type: text/html;charset=utf-8");
$conn = new mysqli("localhost", "root", "px980305", "ajax")or die ("You cannot connect the database!<br>".mysqli_error());
?>

查询数据 list.php

<?php
require 'fun.php';
include "msg.php";
$sql="select * from img";
$result =mysqli_query($conn,$sql);
$num = mysqli_num_rows($result);
$msg=new Msg();
$msg->setnum($num);
if ($num) {
$search_result = array();
while($row = mysqli_fetch_array($result)){
$search_result[] = $row;
}
// 将数组转成json格式
$msg->setdata($search_result);
echo json_encode($msg);
}
?>

ajax实现瀑布流展示图片_html5