瀑布流(Masonry)加上捲到底自動載入,是圖片牆與資訊流的標準配置。經典組合是 Masonry 負責排版、Infinite Scroll 負責觸發載入,兩者搭配 jQuery 使用。
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" />
<script src="js/jquery-1.8.1.min.js"></script>
<script src="js/jquery.masonry.min.js"></script>
<script src="js/jquery.infinitescroll.min.js"></script>
<style>
#container { width: 90%; margin: 80px auto; }
.box {
box-shadow: 0 0 4px #999;
margin-top: 40px;
padding: 40px;
font-family: "Century Gothic", "Microsoft YaHei", Arial, monospace;
}
.loading { text-align: center; }
</style>
<div id="container">
<!-- 第一頁的內容由伺服器輸出 -->
</div>
<div class="loading"></div>
<div id="next-link"><a href="data.php?page=1">下一頁</a></div>
<?php
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$size = 20;
$offset = ($page - 1) * $size;
try {
$pdo = new PDO('mysql:host=localhost;dbname=wechatbook;charset=utf8mb4', 'root', 'root');
$stmt = $pdo->prepare("SELECT title FROM wcb_rss_news LIMIT :offset, :size");
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':size', $size, PDO::PARAM_INT);
$stmt->execute();
$list = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($list as $row) {
?>
<div class="box"><?= htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8') ?></div>
<?php
}
} catch (PDOException $e) {
// 正式環境請寫入日誌,不要直接輸出錯誤訊息
error_log($e->getMessage());
}
?>
原範例把 $offset 直接插入 SQL 字串,雖然是內算出來的整數,但養成用 prepare 綁參數的習慣更安全;輸出到 HTML 時也應經過 htmlspecialchars 轉義。
$(function () {
var $container = $("#container");
// 一定要等圖片載入完,否則高度算不準會導致重疊
$container.imagesLoaded(function () {
$container.masonry({
itemSelector: '.box',
isAnimated: true,
columnWidth: 200,
gutterWidth: 200
// isFitWidth: true, // 自適應寬度
// isResizableL: true // 視窗縮放時重新排版
});
});
$container.infinitescroll({
navSelector: '#next-link', // 分頁連結所在元素
nextSelector: '#next-link a', // 實際的「下一頁」連結
itemSelector: '.box', // 每個要排版的項目
animate: true,
loading: {
msgText: "載入中...",
finishedMsg: '沒有新資料了...',
img: 'img/loading.gif',
selector: '.loading'
},
localMode: true
}, function (newElements) {
var $newEle = $(newElements);
$newEle.imagesLoaded(function () {
$container.masonry('appended', $newEle, true);
});
});
});
最關鍵的一行是 $container.masonry('appended', $newEle, true):新載入的項目必須告訴 Masonry「這些是追加的」,它才會重新計算配置而不破壞既有排版。
.container {
column-count: 4;
column-gap: 16px;
}
.box {
break-inside: avoid;
margin-bottom: 16px;
}
缺點是內容由上而下、由左至右填,閱讀順序是「先填滿第一欄」,與視覺橫向閱讀的習慣不同。
var page = 1;
var observer = new IntersectionObserver(function (entries) {
if (!entries[0].isIntersecting) { return; }
fetch('data.php?page=' + (++page))
.then(r => r.json())
.then(function (items) {
if (!items.length) { observer.disconnect(); return; }
items.forEach(function (it) {
$('.container').append('<div class="box">' + it.title + '</div>');
});
});
}, { rootMargin: '200px' }); // 提前 200px 觸發,載入更順
observer.observe(document.querySelector('.loading'));
imagesLoaded,否則排版會在圖片載入後跳動(layout shift)。new Masonry(el, options)。