


Combining PHP Jquery and ajax to achieve drop-down and fade-out waterfall flow effect [no plug-ins required], jqueryajax_PHP tutorial
Jul 12, 2016 am 08:53 AMPHP Jquery combined with ajax to achieve drop-down and fade-out waterfall flow effect [no plug-in required], jqueryajax
Introduction:
Waterfall flow, also known as waterfall flow layout. It is a relatively popular website page layout. The visual performance is a jagged multi-column layout. As the page scroll bar scrolls down, this layout will continuously load data blocks and append them to the current tail. The first website to adopt this layout was Pinterest, which gradually became popular in the country. Most domestic fresh websites are basically of this style, such as Huaban.com, Mogujie, Meilishuo, etc.
No nonsense, let’s go straight to the code. The entire code is divided into two sections of code. The specific code is as follows.
Front desk:
<?php <br>$category=$this->getMyVal('category',$_GET);<br>$xiaohuaList=Xiaohua::model()->getXiaohao($category); //打開頁(yè)面默認(rèn)顯示的數(shù)據(jù)<br>?><br><br><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為已加載次數(shù),render為渲染接口函數(shù),接受一個(gè)dom集合或jquery對(duì)象作為參數(shù)。通過ajax等異步方法得到的數(shù)據(jù)可以傳入該接口進(jìn)行渲染,如 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>
Backstage:
public function actionListXiaohua() { $xiaohuaList=Xiaohua::model()->getXiaohua();//獲取笑話信息 echo CJSON::encode($xiaohuaList); }
js:
;(function($){ var //參數(shù) setting={ column_width:240,//列寬 column_className:'waterfall_column',//列的類名 column_space:2,//列間距 cell_selector:'.cell',//要排列的磚塊的選擇器,context為整個(gè)外部容器 img_selector:'img',//要加載的圖片的選擇器 auto_imgHeight:true,//是否需要自動(dòng)計(jì)算圖片的高度 fadein:true,//是否漸顯載入 fadein_speed:600,//漸顯速率,單位毫秒 insert_type:1, //單元格插入方式,1為插入最短那列,2為按序輪流插入 getResource:function(index){ } //獲取動(dòng)態(tài)資源函數(shù),必須返回一個(gè)磚塊元素集合,傳入?yún)?shù)為加載的次數(shù) }, // waterfall=$.waterfall={},//對(duì)外信息對(duì)象 $waterfall=null;//容器 waterfall.load_index=0, //加載次數(shù) $.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); //重排已存在元素時(shí)強(qiáng)制不漸顯 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(){//創(chuàng)建列 waterfall.column_num=calculateColumns();//列數(shù) //循環(huán)創(chuàng)建列 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(){//計(jì)算需要的列數(shù) 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){//如果給出了圖片高度,或者是按順序插入,則不必等圖片加載完就能計(jì)算列的高度了 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(){//圖片加載后才能自動(dòng)計(jì)算出尺寸 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等瀏覽器的緩存問題:圖片緩存后不會(huì)再觸發(fā)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(){//計(jì)算最短的那列的索引 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;//延遲滾動(dòng)加載計(jì)時(shí)器 function onScroll(){//滾動(dòng)加載 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;//滾動(dòng)條距離 var windowHeight=document.documentElement.clientHeight||document.body.clientHeight||0;//窗口高度 if(scrollTop>=bottom-windowHeight){ render(getElements(),true); } },100); } function onResize(){//窗口縮放時(shí)重新排列 if(calculateColumns()==waterfall.column_num) return; //列數(shù)未改變,不需要重排 var $cells=waterfall.$waterfall.find(setting.cell_selector); waterfall.$columns.remove(); waterfall.$columns=creatColumn(); render($cells,false); //重排已有元素時(shí)強(qiáng)制不漸顯 } })(jQuery);
The above is the editor’s introduction to the combination of PHP Jquery and ajax to achieve the drop-down and fade-out waterfall flow effect [no plug-ins required]. I hope it will be helpful to you. If you have any questions during the use, Please leave me a message and I will reply to you in time. At the same time, we are also very grateful to everyone for supporting the Bangkejia website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Upgrading the PHP version is actually not difficult, but the key lies in the operation steps and precautions. The following are the specific methods: 1. Confirm the current PHP version and running environment, use the command line or phpinfo.php file to view; 2. Select the suitable new version and install it. It is recommended to install it with 8.2 or 8.1. Linux users use package manager, and macOS users use Homebrew; 3. Migrate configuration files and extensions, update php.ini and install necessary extensions; 4. Test whether the website is running normally, check the error log to ensure that there is no compatibility problem. Follow these steps and you can successfully complete the upgrade in most situations.

TopreventCSRFattacksinPHP,implementanti-CSRFtokens.1)Generateandstoresecuretokensusingrandom_bytes()orbin2hex(random_bytes(32)),savethemin$_SESSION,andincludetheminformsashiddeninputs.2)ValidatetokensonsubmissionbystrictlycomparingthePOSTtokenwiththe

To set up a PHP development environment, you need to select the appropriate tools and install the configuration correctly. ①The most basic PHP local environment requires three components: the web server (Apache or Nginx), the PHP itself and the database (such as MySQL/MariaDB); ② It is recommended that beginners use integration packages such as XAMPP or MAMP, which simplify the installation process. XAMPP is suitable for Windows and macOS. After installation, the project files are placed in the htdocs directory and accessed through localhost; ③MAMP is suitable for Mac users and supports convenient switching of PHP versions, but the free version has limited functions; ④ Advanced users can manually install them by Homebrew, in macOS/Linux systems

To merge two PHP arrays and keep unique values, there are two main methods. 1. For index arrays or only deduplication, use array_merge and array_unique combinations: first merge array_merge($array1,$array2) and then use array_unique() to deduplicate them to finally get a new array containing all unique values; 2. For associative arrays and want to retain key-value pairs in the first array, use the operator: $result=$array1 $array2, which will ensure that the keys in the first array will not be overwritten by the second array. These two methods are applicable to different scenarios, depending on whether the key name is retained or only the focus is on

exit() is a function in PHP that is used to terminate script execution immediately. Common uses include: 1. Terminate the script in advance when an exception is detected, such as the file does not exist or verification fails; 2. Output intermediate results during debugging and stop execution; 3. Call exit() after redirecting in conjunction with header() to prevent subsequent code execution; In addition, exit() can accept string parameters as output content or integers as status code, and its alias is die().

The rational use of semantic tags in HTML can improve page structure clarity, accessibility and SEO effects. 1. Used for independent content blocks, such as blog posts or comments, it must be self-contained; 2. Used for classification related content, usually including titles, and is suitable for different modules of the page; 3. Used for auxiliary information related to the main content but not core, such as sidebar recommendations or author profiles. In actual development, labels should be combined and other, avoid excessive nesting, keep the structure simple, and verify the rationality of the structure through developer tools.

To access session data in PHP, you must first start the session and then operate through the $_SESSION hyperglobal array. 1. The session must be started using session_start(), and the function must be called before any output; 2. When accessing session data, check whether the key exists. You can use isset($_SESSION['key']) or array_key_exists('key',$_SESSION); 3. Set or update session variables only need to assign values ??to the $_SESSION array without manually saving; 4. Clear specific data with unset($_SESSION['key']), clear all data and set $_SESSION to an empty array.

Recursive functions refer to self-call functions in PHP. The core elements are 1. Defining the termination conditions (base examples), 2. Decomposing the problem and calling itself recursively (recursive examples). It is suitable for dealing with hierarchical structures, disassembling duplicate subproblems, or improving code readability, such as calculating factorials, traversing directories, etc. However, it is necessary to pay attention to the risks of memory consumption and stack overflow. When writing, the exit conditions should be clarified, the basic examples should be gradually approached, the redundant parameters should be avoided, and small inputs should be tested. For example, when scanning a directory, the function encounters a subdirectory and calls itself recursively until all levels are traversed.
