大家在用这个东西的时候一定要计得有这么几个文件,一个是jquery.js 还有就是你自己数据库的密码。和相对应的图片才可以正常看到效果。下面就是这里所有的代码!!!
HTML文件:waterfall.html
View Code
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>瀑布流-Derek</title> 6 <script type="text/javascript" language="javascript" src="jquery.js"></script> 7 <link type="text/css" rel="stylesheet" href="waterfall.css" /> 8 <script type="text/javascript" language="javascript" src="waterfall.js"></script> 9 </head> 10 <body> 11 12 <ul id="stage"> 13 <li></li> 14 <li></li> 15 <li></li> 16 <li></li> 17 </ul> 18 19 </body> 20 </html>
Javascript文件:waterfall.js
1 $(function(){ 2 jsonajax(); 3 }); 4 5 //这里就要进行计算滚动条当前所在的位置了。如果滚动条离最底部还有100px的时候就要进行调用ajax加载数据 6 $(window).scroll(function(){ 7 //此方法是在滚动条滚动时发生的函数 8 // 当滚动到最底部以上100像素时,加载新内容 9 var $doc_height,$s_top,$now_height; 10 $doc_height = $(document).height(); //这里是document的整个高度 11 $s_top = $(this).scrollTop(); //当前滚动条离最顶上多少高度 12 $now_height = $(this).height(); //这里的this 也是就是window对象 13 if(($doc_height - $s_top - $now_height) < 100) jsonajax(); 14 }); 15 16 17 //做一个ajax方法来请求data.php不断的获取数据 18 var $num = 0; 19 function jsonajax(){ 20 21 $.ajax({ 22 url:'data.php', 23 type:'POST', 24 data:"num="+$num++, 25 dataType:'json', 26 success:function(json){ 27 if(typeof json == 'object'){ 28 var neirou,$row,iheight,temp_h; 29 for(var i=0,l=json.length;i<l;i++){ 30 neirou = json[i]; //当前层数据 31 //找了高度最少的列做添加新内容 32 iheight = -1; 33 $("#stage li").each(function(){ 34 //得到当前li的高度 35 temp_h = Number($(this).height()); 36 if(iheight == -1 || iheight >temp_h){ 37 iheight = temp_h; 38 $row = $(this); //此时$row是li对象了 39 } 40 }); 41 $item = $('<div><img src="'+neirou.img+'" border="0" ><br/>'+neirou.title+'</div>').hide(); 42 $row.append($item); 43 $item.fadeIn(); 44 } 45 } 46 } 47 }); 48 }
CSS文件:waterfall.css
1 body{text-align:center;} 2 /*Download by http://www.codefans.net*/ 3 #stage{ margin:0 auto; padding:0; width:880px; } 4 #stage li{ margin:0; padding:0; list-style:none;float:left; width:220px;} 5 #stage li div{ font-size:12px; padding:10px; color:#999999; text-align:left; }
当然最后就是各位都熟悉的文件--php
1 <?php 2 $link = mysql_connect("localhost","root",""); 3 $sql = "use waterfall"; 4 mysql_query($sql,$link); 5 $sql = "set names utf8"; 6 mysql_query($sql,$link); 7 $num = $_POST['num'] *10; 8 if($_POST['num'] != 0) $num +1; 9 $sql = "select img,title from content limit ".$num.",10"; 10 $result = mysql_query($sql,$link); 11 $temp_arr = array(); 12 while($row = mysql_fetch_assoc($result)){ 13 $temp_arr[] = $row; 14 } 15 $json_arr = array(); 16 foreach($temp_arr as $k=>$v){ 17 $json_arr[] = (object)$v; 18 } 19 //print_r($json_arr); 20 echo json_encode( $json_arr );
大家按这个目录就可以看到效果了。方式很简单但却实很是实用,不管在用户体验还是在处于用户过多的情况下都可以采用这一种方式。一次性读上百条数据,在几个人的情况下还是可以跑起来但是用户过多的话不好说了。呵呵 不多说大家有机会看的话做做就知道了。