使图片保持固定宽度并利用ajax实现动态无限加载
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>固定列数瀑布流</title>
<script src="./ajax.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
window.onload=function(){
//获取页面元素
var oBox=document.getElementById("box");
var oUl=document.getElementsByTagName('ul');
var vH=document.documentElement.clientHeight;
//求出最小高度的列
function min_height(oUl){
var ht=oUl[0].offsetHeight;
var index=0;
for(var i=0;i<oUl.length;i++){
if(oUl[i].offsetHeight<ht){
ht=oUl[i].offsetHeight;
index=i;
}
}
return index;
}
//加载图片
function loadImg(){
ajax('index.json',function(data){
data=(new Function('return'+data))();//将字符串解析成json对象
for(var i=0;i<data.length;i++){
var oLi=document.createElement('li');
var oImg=document.createElement('img');
oImg.src=data[i];
oLi.appendChild(oImg);
oUl[min_height(oUl)].appendChild(oLi);
}
})
}
document.onscroll=function(){
var sH=document.documentElement.scrollTop || document.body.scrollTop;
if(sH+vH>=document.body.scrollHeight*0.8){
loadImg();
}
}
loadImg();
}
</script>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
li{
list-style: none;
}
#box{
margin: 0 auto;
width: 700px;
}
ul{
width: 200px;
float: left;
margin: 0 auto;
margin-right: 10px;
}
img{
width: 200px;
padding-top: 10px;
}
</style>
</head>
<body>
<div id="box">
<ul></ul>
<ul>
</ul>
<ul></ul>
</div>
</body>
</html>
ajax.js:
function ajax(url,fn){
var xhr=window.XMLHttpRequest ?new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");//兼容性
xhr.open('GET',url,true);
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState===4 && xhr.status==200){
fn && fn(xhr.responseText);
}
}
}
index.json:
[
"img1/img%20(17).jpg",
"img1/img%20(2).jpg",
"img1/img%20(3).jpg",
"img1/img%20(4).jpg",
"img1/img%20(5).jpg",
"img1/img%20(6).jpg",
"img1/img%20(7).jpg",
"img1/img%20(8).jpg",
"img1/img%20(9).jpg",
"img1/img%20(10).jpg",
"img1/img%20(11).jpg",
"img1/img%20(12).jpg",
"img1/img%20(13).jpg",
"img1/img%20(14).jpg",
"img1/img%20(15).jpg",
"img1/img%20(16).jpg",
"img1/img%20(18).jpg",
"img1/img%20(19).jpg",
"img1/img%20(20).jpg",
"img1/img%20(21).jpg",
"img1/img%20(22).jpg",
"img1/img%20(23).jpg",
"img1/img%20(24).jpg",
"img1/img%20(25).jpg",
"img1/img%20(26).jpg",
"img1/img%20(27).jpg",
"img1/img%20(28).jpg",
"img1/img%20(29).jpg",
"img1/img%20(30).jpg",
"img1/img%20(31).jpg",
"img1/img%20(32).jpg",
"img1/img%20(33).jpg",
"img1/img%20(34).jpg"
]
效果: