PHP结合Jquery和ajax实现瀑布流特效


Posted in PHP onJanuary 07, 2016

不废话,直接上代码,

前台:

<?php 
$category=$this->getMyVal('category',$_GET);
$xiaohuaList=Xiaohua::model()->getXiaohao($category); //打开页面默认显示的数据
?>
<div id="waterfall">
  <?php foreach ($xiaohuaList as $xiaohua):?>
    <?php $q_id=$xiaohua->id;?>
    <div class="cell m-bg item-h border_h">
      <div class="border-solid-b padding-b-5 text-center"><span class="g-bg glyphicon glyphicon-sunglasses margin-r-5" aria-hidden="true"></span><strong class="color-5 fx_t_<?php echo $q_id;?>"><?php echo CHtml::encode($xiaohua->title);?></strong></div>
      <div class="padding-t-5 fx_c_<?php echo $q_id;?>"><?php echo $xiaohua->content;?></div>
      <div class="padding-t-5 text-right"><span onclick="fx(<?php echo $q_id;?>);" class="fx cursor_p" data-id="<?php echo $q_id;?>"><span class="g-bg glyphicon glyphicon-share-alt margin-r-5" aria-hidden="true"></span>分享</span></div>
    </div>
  <?php endforeach;?>
</div>
<script>
var opt={
 getResource:function(index,render){//index为已加载次数,render为渲染接口函数,接受一个dom集合或jquery对象作为参数。通过ajax等异步方法得到的数据可以传入该接口进行渲染,如 render(elem)
   var html='';
   var _url='<?php echo $this->createUrl('listXiaohua');?>';
   $.ajax({
    type: "get",
    url: _url,
    dataType : "json",
    async:false,
    success: function(data){
      for( var i in data){
        var q_id=data[i].id;
        html+='<div class="cell m-bg item-h border_h"><div class="border-solid-b padding-b-5 text-center"><span class="g-bg glyphicon glyphicon-sunglasses margin-r-5" aria-hidden="true"></span><strong class="color-5 fx_t_'+q_id+'">'+data[i].title+'</strong></div><div class="padding-t-5 fx_c_'+q_id+'">'+data[i].content+'</div>'
           +'<div class="padding-t-5 text-right"><span onclick="fx('+q_id+');" class="fx cursor_p" data-id="'+q_id+'"><span class="g-bg glyphicon glyphicon-share-alt margin-r-5" aria-hidden="true"></span>分享</span></div></div>';
      }
   }});
   return $(html);
 },
 column_width:376,
 column_space:10,
 auto_imgHeight:true,
 insert_type:1
}
$('#waterfall').waterfall(opt);
</script>

后台:

public function actionListXiaohua() {
  $xiaohuaList=Xiaohua::model()->getXiaohua();//获取笑话信息
  echo CJSON::encode($xiaohuaList);
}

js:

(function($){
  var
  //参数
  setting={
   column_width:240,//列宽
   column_className:'waterfall_column',//列的类名
   column_space:2,//列间距
   cell_selector:'.cell',//要排列的砖块的选择器,context为整个外部容器
   img_selector:'img',//要加载的图片的选择器
   auto_imgHeight:true,//是否需要自动计算图片的高度
   fadein:true,//是否渐显载入
   fadein_speed:600,//渐显速率,单位毫秒
   insert_type:1, //单元格插入方式,1为插入最短那列,2为按序轮流插入
   getResource:function(index){ } //获取动态资源函数,必须返回一个砖块元素集合,传入参数为加载的次数
  },
  //
  waterfall=$.waterfall={},//对外信息对象
  $waterfall=null;//容器
  waterfall.load_index=0, //加载次数
  $.fn.extend({
    waterfall:function(opt){
     opt=opt||{};
     setting=$.extend(setting,opt);
     $waterfall=waterfall.$waterfall=$(this);
     waterfall.$columns=creatColumn();
     render($(this).find(setting.cell_selector).detach(),false); //重排已存在元素时强制不渐显
     waterfall._scrollTimer2=null;
     $(window).bind('scroll',function(){
       clearTimeout(waterfall._scrollTimer2);
       waterfall._scrollTimer2=setTimeout(onScroll,300);
     });
     waterfall._scrollTimer3=null;
     $(window).bind('resize',function(){
       clearTimeout(waterfall._scrollTimer3);
       waterfall._scrollTimer3=setTimeout(onResize,300);
     });
    }
  });
  function creatColumn(){//创建列
   waterfall.column_num=calculateColumns();//列数
   //循环创建列
   var html='';
   for(var i=0;i<waterfall.column_num;i++){
     html+='<div class="'+setting.column_className+'" style="width:'+setting.column_width+'px; display:inline-block; *display:inline;zoom:1; margin-left:'+setting.column_space/2+'px;margin-right:'+setting.column_space/2+'px; vertical-align:top; overflow:hidden"></div>';
   }
   $waterfall.prepend(html);//插入列
   return $('.'+setting.column_className,$waterfall);//列集合
  }
  function calculateColumns(){//计算需要的列数
   var num=Math.floor(($waterfall.innerWidth())/(setting.column_width+setting.column_space));
   if(num<1){ num=1; } //保证至少有一列
   return num;
  }
  function render(elements,fadein){//渲染元素
   if(!$(elements).length) return;//没有元素
   var $columns = waterfall.$columns;
   $(elements).each(function(i){
     if(!setting.auto_imgHeight||setting.insert_type==2){//如果给出了图片高度,或者是按顺序插入,则不必等图片加载完就能计算列的高度了
       if(setting.insert_type==1){
        insert($(elements).eq(i),setting.fadein&&fadein);//插入元素
       }else if(setting.insert_type==2){
        insert2($(elements).eq(i),i,setting.fadein&&fadein);//插入元素
       }
       return true;//continue
     }
     if($(this)[0].nodeName.toLowerCase()=='img'||$(this).find(setting.img_selector).length>0){//本身是图片或含有图片
       var image=new Image;
       var src=$(this)[0].nodeName.toLowerCase()=='img'?$(this).attr('src'):$(this).find(setting.img_selector).attr('src');
       image.onload=function(){//图片加载后才能自动计算出尺寸
         image.onreadystatechange=null;
         if(setting.insert_type==1){
           insert($(elements).eq(i),setting.fadein&&fadein);//插入元素
         }else if(setting.insert_type==2){
           insert2($(elements).eq(i),i,setting.fadein&&fadein);//插入元素
         }
         image=null;
       }
       image.onreadystatechange=function(){//处理IE等浏览器的缓存问题:图片缓存后不会再触发onload事件
         if(image.readyState == "complete"){
           image.onload=null;
           if(setting.insert_type==1){
            insert($(elements).eq(i),setting.fadein&&fadein);//插入元素
           }else if(setting.insert_type==2){
            insert2($(elements).eq(i),i,setting.fadein&&fadein);//插入元素
           }
           image=null;
         }
       }
       image.src=src;
     }else{//不用考虑图片加载
       if(setting.insert_type==1){
         insert($(elements).eq(i),setting.fadein&&fadein);//插入元素
       }else if(setting.insert_type==2){
         insert2($(elements).eq(i),i,setting.fadein&&fadein);//插入元素
       }
     }
   });
  }
  function public_render(elems){//ajax得到元素的渲染接口
   render(elems,true);
  }
  function insert($element,fadein){//把元素插入最短列
   if(fadein){//渐显
     $element.css('opacity',0).appendTo(waterfall.$columns.eq(calculateLowest())).fadeTo(setting.fadein_speed,1);
   }else{//不渐显
     $element.appendTo(waterfall.$columns.eq(calculateLowest()));
   }
  }
  function insert2($element,i,fadein){//按序轮流插入元素
   if(fadein){//渐显
     $element.css('opacity',0).appendTo(waterfall.$columns.eq(i%waterfall.column_num)).fadeTo(setting.fadein_speed,1);
   }else{//不渐显
     $element.appendTo(waterfall.$columns.eq(i%waterfall.column_num));
   }
  }
  function calculateLowest(){//计算最短的那列的索引
   var min=waterfall.$columns.eq(0).outerHeight(),min_key=0;
   waterfall.$columns.each(function(i){
     if($(this).outerHeight()<min){
      min=$(this).outerHeight();
      min_key=i;
     }
   });
   return min_key;
  }
  function getElements(){//获取资源
   $.waterfall.load_index++;
   return setting.getResource($.waterfall.load_index,public_render);
  }
  waterfall._scrollTimer=null;//延迟滚动加载计时器
  function onScroll(){//滚动加载
   clearTimeout(waterfall._scrollTimer);
   waterfall._scrollTimer=setTimeout(function(){
     var $lowest_column=waterfall.$columns.eq(calculateLowest());//最短列
     var bottom=$lowest_column.offset().top+$lowest_column.outerHeight();//最短列底部距离浏览器窗口顶部的距离
     var scrollTop=document.documentElement.scrollTop||document.body.scrollTop||0;//滚动条距离
     var windowHeight=document.documentElement.clientHeight||document.body.clientHeight||0;//窗口高度
     if(scrollTop>=bottom-windowHeight){
       render(getElements(),true);
     }
   },100);
  }
  function onResize(){//窗口缩放时重新排列
   if(calculateColumns()==waterfall.column_num) return; //列数未改变,不需要重排
   var $cells=waterfall.$waterfall.find(setting.cell_selector);
   waterfall.$columns.remove();
   waterfall.$columns=creatColumn();
   render($cells,false); //重排已有元素时强制不渐显
  }
})(jQuery);

好了,全部完成了。

再给大家分享一个吧

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>定宽Jquery+AJAX+JSON瀑布流布局(每行代码都有详细注释)</title>
<style type="text/css">
body, ul, li, h3 { margin: 0; padding: 0; list-style: none; font: bold 12px "微软雅黑"; }
/*瀑布流布局样式*/
#lxf-box { position: relative; width: 1000px; margin:0 auto;}
#lxf-box li { background: #fff; border: solid 1px #ccc; text-align: center; padding: 10px; float: left;}
h3 { padding-top: 8px; }
img { width: 200px; height: auto; display: block; border: 0 }
/*css3动画 注由于是css3制作的所以兼容性不保证 要想兼容性好 请自己做成gif动画加载图*/
/*li { -webkit-transition: all .7s ease-out .1s; -moz-transition: all .7s ease-out; -o-transition: all .7s ease-out .1s; transition: all .7s ease-out .1s }*/
#loading { display:none; line-height: 30px; background: #000; color:#fff; text-align: center; height: 30px; width: 100%; position:fixed; bottom:0; opacity:0.8;}
</style>
<script src="/templets/niu/js/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<h1 color="red">预览无效果请刷新</h1>
<ul id="lxf-box">
 <li><a href="div_css/342.html"><img src="/uploads/allimg/120814/1-120Q411544TX.jpg"></a>
  <h3>图片标题</h3>
 </li>
 <li><a href="/ajax/237.html"><img src="/uploads/allimg/120801/1-120P1223013157.jpg"></a>
  <h3>图片标题</h3>
 </li>
 <li><a href="/js_ad/271.html/"><img src="/uploads/allimg/120808/1-120PP00915a2.jpg"></a>
  <h3>图片标题</h3>
 </li>
 <li><a href="/js_texiao/312.html/"><img src="/uploads/allimg/120812/1-120Q2150022G8.jpg"></a>
  <h3>图片标题</h3>
 </li>
 <li><a href="/js_pic/191.html/"><img src="/uploads/allimg/120722/1-120H2144003129.jpg"></a>
  <h3>图片标题</h3>
 </li>
 <li><a href="/js_pic/318.html/"><img src="/uploads/allimg/120812/1-120Q2161941b2.jpg"></a>
  <h3>图片标题</h3>
 </li>
 <li><a href="/div_css/341.html/"><img src="/uploads/allimg/120814/1-120Q4113240U2.jpg"></a>
  <h3>图片标题</h3>
 </li>
 <li><a href="/div_css/350.html/"><img src="/uploads/allimg/120814/125411K11-2.png"></a>
  <h3>图片标题</h3>
 </li>
 <li><a href="/div_css/350.html/"><img src="/uploads/allimg/120814/1254113249-12.png"></a>
  <h3>图片标题</h3>
 </li>
 <li><a href="/div_css/349.html/"><img src="/uploads/allimg/120814/12500a292-1.png"></a>
  <h3>图片标题</h3>
 </li>
 <li>img src="/uploads/allimg/120813/1-120Q3145U0938.jpg">
  <h3>图片标题</h3>
 </li>
 <li><a href="/div_css/344.html/"><img src="/uploads/allimg/120814/12353B521-0.jpg"></a>
  <h3>图片标题</h3>
 </li>
</ul>
<div id="loading">正在加载……</div>
<script>
/*
原理:1.把所有的li的高度值放到数组里面
   2.第一行的top都为0
   3.计算高度值最小的值是哪个li
   4.把接下来的li放到那个li的下面
编写时间:2012年6月9日
*/
 
function iiwnet(){//定义成函数便于调用
var wrap = document.getElementById("lxf-box")
var margin = 10;//这里设置间距
var li=$("li");//这里是区块名称
var li_W = li[0].offsetWidth+margin;//取区块的实际宽度(包含间距,这里使用源生的offsetWidth函数,不适用jQuery的width()函数是因为它不能取得实际宽度,例如元素内有pandding就不行了)
var h=[];//记录区块高度的数组
  li.css("position","absolute");
  var n = wrap.offsetWidth/li_W|0;//容器的宽度除以区块宽度就是一行能放几个区块
  for(var i = 0;i < li.length;i++) {//有多少个li就循环多少次
    li_H = li[i].offsetHeight;//获取每个li的高度
    if(i < n) {//n是一行最多的li,所以小于n就是第一行了
      h[i]=li_H;//把每个li放到数组里面
      li.eq(i).css("top",0);//第一行的Li的top值为0
      li.eq(i).css("left",i * li_W);//第i个li的左坐标就是i*li的宽度
      }
    else{
      min_H =Math.min.apply(null,h) ;//取得数组中的最小值,区块中高度值最小的那个
      minKey = getarraykey(h, min_H);//最小的值对应的指针
      h[minKey] += li_H+margin ;//加上新高度后更新高度值
      li.eq(i).css("top",min_H+margin);//先得到高度最小的Li,然后把接下来的li放到它的下面
      li.eq(i).css("left",minKey * li_W); //第i个li的左坐标就是i*li的宽度
    }
    $("h3").eq(i).text("编号:"+i+",高度:"+li_H);//把区块的序号和它的高度值写入对应的区块H3标题里面
    $("li").animate({opacity:1});
  }
}
/* 使用for in运算返回数组中某一值的对应项数(比如算出最小的高度值是数组里面的第几个) */
function getarraykey(s, v) {for(k in s) {if(s[k] == v) {return k;}}}
/*这里一定要用onload,因为图片不加载完就不知道高度值*/
window.onload = function() {iiwnet();};
/*浏览器窗口改变时也运行函数*/
window.onresize = function() {iiwnet();};
 
/**********************************************************************/
/*无限加载*/
var i=1;
function getMore(){
  $("#loading").show();  
  var json = "https://3water.com/images/jstx/img.js";
    $.getJSON(json, function(data){ 
        $.each(data,function(i){
        var url=data[i].url;  
        var html="<li style='opacity:0'><a href='https://3water.com/'><img src="+url+" ></a><h3>图片标题</h3></li>";    
      $("#lxf-box").append(html);   
          $("#loading").hide();
        });
        iiwnet();
        i=1
    });
  };
  /*滚动到底部的时候*/
   $(window).bind("scroll",function(){
  if( $(document).scrollTop() + $(window).height() > $(document).height() - 10 && i==1) {
    i=0;
    getMore();
     
    }
   });
</script>
</body>
</html>
<p align="center"><font color=red>如果运行效果无非显示请点击【刷新页面】</font><br/>【<a href="https://3water.com" target="_blank"><font color="#666666">返回首页</font></a>】【<a href="javascript:this.location.reload()"><font color="#666666">刷新本页</font></a>】【<a href="javascript:window.scroll(0,0)"><font color="#666666">返回顶部</font></a>】【<a href="javascript:window.close()"><font color="#666666">关闭本页</font></a>】</p>
PHP 相关文章推荐
PHP的cURL库功能简介 抓取网页、POST数据及其他
Apr 07 PHP
PHP 删除文件与文件夹操作 unlink()与rmdir()这两个函数的使用
Jul 17 PHP
php curl post 时出现的问题解决
Jan 30 PHP
一个比较不错的PHP日历类分享
Nov 18 PHP
浅谈php错误提示及查错方法
Jul 14 PHP
基于PHP如何把汉字转化为拼音
Dec 11 PHP
thinkphp3.2点击刷新生成验证码
Feb 16 PHP
Thinkphp框架开发移动端接口(2)
Aug 18 PHP
PHP中数组转换为SimpleXML教程
Jan 27 PHP
laravel excel 上传文件保存到本地服务器功能
Nov 14 PHP
PHP实现常用排序算法的方法
Feb 05 PHP
thinkphp5 框架结合plupload实现图片批量上传功能示例
Apr 04 PHP
我整理的PHP 7.0主要新特性
Jan 07 #PHP
php上传图片生成缩略图(GD库)
Jan 06 #PHP
joomla数据库操作示例代码
Jan 06 #PHP
Yii清理缓存的方法
Jan 06 #PHP
yii实现model添加默认值的方法(2种方法)
Jan 06 #PHP
如何使用微信公众平台开发模式实现多客服
Jan 06 #PHP
基于PHP技术开发客服工单系统
Jan 06 #PHP
You might like
用PHP实现多服务器共享SESSION数据的方法
2007/03/16 PHP
thinkPHP下的widget扩展用法实例分析
2015/12/26 PHP
Laravel使用memcached缓存对文章增删改查进行优化的方法
2016/10/08 PHP
利用PHP访问MySql数据库的逻辑操作以及增删改查的实例讲解
2017/08/30 PHP
使用PHPWord生成word文档的方法详解
2019/06/06 PHP
JS面向对象基础讲解(工厂模式、构造函数模式、原型模式、混合模式、动态原型模式)
2014/08/16 Javascript
js+HTML5基于过滤器从摄像头中捕获视频的方法
2015/06/16 Javascript
IE10中flexigrid无法显示数据的解决方法
2015/07/26 Javascript
Jquery使用小技巧汇总
2015/12/29 Javascript
@ResponseBody 和 @RequestBody 注解的区别
2017/03/08 Javascript
jquery实现图片平滑滚动详解
2017/03/22 jQuery
详解vue2父组件传递props异步数据到子组件的问题
2017/06/29 Javascript
mui开发中获取单选按钮、复选框的值(实例讲解)
2017/07/24 Javascript
带你快速理解javascript中的事件模型
2017/08/14 Javascript
理解Koa2中的async&amp;await的用法
2018/02/05 Javascript
layui添加动态菜单与选项卡
2019/07/26 Javascript
vue.js基于v-for实现批量渲染 Json数组对象列表数据示例
2019/08/03 Javascript
浅谈vue3中effect与computed的亲密关系
2019/10/10 Javascript
jQuery实现可以计算进制转换的计算器
2020/10/19 jQuery
[53:15]Mineski vs iG 2018国际邀请赛小组赛BO2 第二场 8.16
2018/08/17 DOTA
Python3实现生成随机密码的方法
2014/08/23 Python
python 怎样将dataframe中的字符串日期转化为日期的方法
2019/09/26 Python
Matplotlib使用字符串代替变量绘制散点图的方法
2020/02/17 Python
PyCharm中Matplotlib绘图不能显示UI效果的问题解决
2020/03/12 Python
Tensorflow tf.nn.atrous_conv2d如何实现空洞卷积的
2020/04/20 Python
Python爬虫之Selenium设置元素等待的方法
2020/12/04 Python
家乐福巴西网上超市:Carrefour巴西
2016/10/31 全球购物
Pat McGrath Labs官网:世界上最有影响力的化妆师推出的彩妆品牌
2018/01/07 全球购物
香奈儿美国官网:CHANEL美国
2020/05/20 全球购物
如何现实servlet的单线程模式
2014/08/05 面试题
消防战士优秀事迹材料
2014/02/13 职场文书
共产党员公开承诺书范文
2014/03/28 职场文书
党员一句话承诺大全
2014/03/28 职场文书
副总经理任命书
2014/06/05 职场文书
React列表栏及购物车组件使用详解
2021/06/28 Javascript
win10如何更改appdata文件夹的默认位置?
2022/07/15 数码科技