首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP + jQuery + Ajax 實現瀑布流無限加載完整實例

     編輯:PHP 相關知識

效果預覽

頁面初始加載若干數據,滾動到底部自動觸發 Ajax 請求追加數據,配合 CSS 多列布局呈現 Pinterest 風格瀑布流。

前端頁面結構與初始化

<div id="waterfall">
<?php foreach ($xiaohuaList as $xiaohua): ?>
    <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"></span>
            <strong class="color-5 fx_t_<?php echo $xiaohua->id; ?>"><?php echo CHtml::encode($xiaohua->title); ?></strong>
        </div>
        <div class="padding-t-5 fx_c_<?php echo $xiaohua->id; ?>"><?php echo $xiaohua->content; ?></div>
        <div class="padding-t-5 text-right">
            <span onclick="fx(<?php echo $xiaohua->id; ?>);" class="fx cursor_p" data-id="<?php echo $xiaohua->id; ?>">
                <span class="g-bg glyphicon glyphicon-share-alt margin-r-5"></span>分享
            </span>
        </div>
    </div>
<?php endforeach; ?>
</div>

瀑布流插件配置與 Ajax 獲取數據

<script>
var opt = {
    getResource: function(index, render) {
        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"></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"></span>分享</span></div></div>';
                }
            }
        });
        return $(html);
    },
    column_width: 376,      // 列寬
    column_space: 10,       // 列間距
    auto_imgHeight: true,   // 自動計算圖片高度
    insert_type: 1          // 1=插入最短列,2=輪流插入
};
$('#waterfall').waterfall(opt);
</script>

後端控制器動作

public function actionListXiaohua() {
    $xiaohuaList = Xiaohua::model()->getXiaohua(); // 獲取笑話數據
    echo CJSON::encode($xiaohuaList); // 返回 JSON
}

核心瀑布流插件代碼 (jquery.waterfall.js)

插件核心邏輯:

  • 列管理:根據容器寬度動態計算列數,創建列容器。
  • 智慧插入:insert_type:1 總是插入當前最短列;insert_type:2 輪流插入。
  • 圖片高度自適應:auto_imgHeight:true 時,等待圖片加載完成後再計算高度並插入,防止佈局錯亂。
  • 滾動加載:監聽 scroll 事件,判斷最短列底部進入可視區則觸發 getResource 獲取新數據。
  • 窗口縮放重排:resize 事件觸發重新計算列數並重排現有元素。
(function($){
    var setting = { column_width:240, column_className:'waterfall_column', column_space:2, cell_selector:'.cell', img_selector:'img', auto_imgHeight:true, fadein:true, fadein_speed:600, insert_type:1, getResource:function(index){} };
    var waterfall = { load_index:0, $waterfall:null, $columns:null, column_num:0, _scrollTimer:null, _scrollTimer2:null, _scrollTimer3:null };
    $.fn.extend({
        waterfall: function(opt) {
            opt = opt || {}; setting = $.extend(setting, opt);
            waterfall.$waterfall = $(this); waterfall.$columns = creatColumn();
            render($(this).find(setting.cell_selector).detach(), false);
            $(window).bind('scroll', function(){ clearTimeout(waterfall._scrollTimer2); waterfall._scrollTimer2 = setTimeout(onScroll, 300); });
            $(window).bind('resize', function(){ clearTimeout(waterfall._scrollTimer3); waterfall._scrollTimer3 = setTimeout(onResize, 300); });
        }
    });
    // ... creatColumn, calculateColumns, render, insert, insert2, calculateLowest, getElements, onScroll, onResize 等內部函數 ...
})(jQuery);

附贈:原生 JS 實現的簡易瀑布流(無依賴)

適合不想引入 jQuery 的輕量級場景,核心邏輯:記錄每列高度數組,新元素總放入最短列。

function iiwnet() {
    var wrap = document.getElementById("lxf-box"), margin = 10;
    var li = document.getElementsByTagName("li");
    var li_W = li[0].offsetWidth + margin;
    var h = []; // 列高數組
    for(var i=0; i $(document).height() - 10 && i==1) {
        i=0; getMore();
    }
});

總結

本文提供了基於 jQuery 插件的完整瀑布流方案(含後端接口),並附贈原生 JS 版本。關鍵點在於:

  1. 後端返回結構化 JSON,前端模板渲染 HTML 片段。
  2. 插件自動處理多列佈局、圖片高度、滾動觸發、窗口縮放重排。
  3. getResource 回調設計靈活,可對接任意分頁 API。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved