目的:利用ajax插件做一个瀑布流的布局,熟悉ajax的使用。
效果图:
原理:
图片块的插入方式
加载第二页数据的时机判断
用到的工具:
1. H5Builder
2.WampServer(用于建立本地服务器)
布局样式部分:
<body> <div class="box"> <ul id="ul1"> <li></li> <li></li> <li></li> <li></li> </ul> </div> </body><style> * { margin: 0; padding: 0; list-style: none; } .box { width: 1000px; height: 2000px; margin: 50px auto; background: #212121; } ul { width: 100%; } li { float: left; width: 250px; } div { width: 96%; padding: 2%; background: #808080 } div img { width: 100%; } 准备文件:
1.ajax.js
function ajax(method, url, data, success) { var xhr = null; try { xhr = new XMLHttpRequest(); } catch (e) { 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('出错了,Err:' + xhr.status); } } } }
2.getPics.php(数据文件接口)
<?php header('Content-type:text/html; charset="utf-8"'); /* API: getPics.php 参数 cpage : 获取数据的页数 */ $cpage = isset($_GET['cpage']) ? $_GET['cpage'] : 1; $url = 'http://www.wookmark.com/api/json/popular?page=' . $cpage; $content = file_get_contents($url); $content = iconv('gbk', 'utf-8', $content); echo $content; ?> 编写js函数: <script src="ajax.js"></script> <script type="text/javascript"> window.onload = function() { var oUl = document.getElementById('ul1'); var aLi = oUl.getElementsByTagName('li'); var iPage = 1; var b = true;//设置一个参数用于判断是否加载更多的页面数据 getList(); //获取图片列表数据与插入 function getList() { ajax('get', 'getPics.php', 'cpage=' + iPage, function(data) { var arr = JSON.parse(data); for(var i=0;i<arr.length;i++){ var _index=getShort(); var oDiv=document.createElement('div'); var oImg=document.createElement('img'); oImg.src=arr[i].preview; oImg.style.width='200px'; oImg.style.height=arr[i].height*(200/arr[i].width)+'px'; oDiv.appendChild(oImg); var oP=document.createElement('p'); oP.innerHTML=arr[i].title; oDiv.appendChild(oP); aLi[_index].appendChild(oDiv); } if(!arr.lenth){ return; } b=true; }) } //当滚动至底部时候加载更多的数据 window.οnscrοll=function(){ var _index=getShort(); var oLi=aLi[_index]; var scrollTop=document.documentElement.scrollTop||document.body.scrollTop; if(getTop(oLi)+oLi.offsetHeight<document.documentElement.clientHeight+scrollTop){ if(b){ b=false; iPage++; getList(); } } } //取得最短的图片 function getShort(){ var index=0; var ih=aLi[index].offsetHeight; for(var i=1;i<aLi.length;i++){ if(aLi[i].offsetHeight<ih){ index=i; ih=aLi[i].offsetHeight; } } return index; } //获取当前内容的最高高度 function getTop(obj){ var iTop=0; while(obj){ iTop+=obj.offsetTop; obj=obj.offsetParent; } return iTop; } } </script>