原生JS写的一个瀑布流布局

<!DOCTYPE html> <html> <head> <title>瀑布流布局</title> <meta charset="UTF-8"/> <style> *{ padding:0; margin:0; } body{ font-family:"微软雅黑"; } #oUl{ width: 1080px; overflow: hidden; margin: 100px auto 0; } #oUl li{ width: 247px; list-style: none; float: left; margin-left: 10px; } #oUl li div { padding: 10px; margin-bottom: 10px; border:1px solid red; } #oUl li div img { width: 225px; display: block; } #oUl li div p { text-align: center; } </style> </head> <body> <ul id="oUl"> <li></li> <li></li> <li></li> <li></li> </ul> </body> </html> <script> window.onload=function(){ var oUl=document.getElementById('oUl'); var aLi=oUl.getElementsByTagName('li'); var iLen=aLi.length; var iPage=2; var b=true; //初始化 getList(); function getList(){ ajax('get','getPics.php','cpage'+iPage,function(data){ var data=JSON.parse(data); //console.log(data); for(var i=0;i<data.length;i++){ var _index=getShort(); var oDiv=document.createElement('div'); var oImg=document.createElement('img'); oImg.src=data[i].preview; oImg.style.width='225px'; oImg.style.height=data[i].height*(225/data[i].width)+'px'; oDiv.appendChild(oImg); var oP=document.createElement('p'); oP.innerHTML=data[i].title; oDiv.appendChild(oP); aLi[_index].appendChild(oDiv); } b=true; }) } //获取最小li的高度 function getShort(){ var index=0; var iH=aLi[index].offsetHeight; for(var i=0;i<iLen;i++){ if(iH>aLi[i].offsetHeight){ index=i; iH=aLi[i].offsetHeight; } } return index; } //加载下一页 window.onscroll=function(){ var _index=getShort(); var oLi=aLi[_index]; var Scroll=document.documentElement.scrollTop||document.body.scrollTop; if(getTop(oLi)+oLi.offsetHeight>document.documentElement.clientHeight+Scroll){ if(b){ b=false; iPage++; getList(); } } } function getTop(obj){ var iTop=0; while(obj){ iTop+=obj.offsetHeight; obj=obj.offsetParent; } return iTop; } } function ajax(method,url,data,success){ var xhr=null; if(window.XMLHttpRequest){ xhr=new XMLHttpRequest(); }else{ xhr=new ActiveXObject('Microsoft.XMLHTTP') ; } if(method=='get'&&data){ url+='?'+data; } xhr.open(method,url,true); if(method=='get'){ xhr.send(); }else{ xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); xhr.send(data); } xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status==200){ success&&success(xhr.responseText); }else{ alert('Eorre'+xhr.status); } } } } </script>