瀑布流分页是一种网页布局方式,其中内容以不规则的矩形块(通常称为“卡片”)排列,这些卡片会垂直堆叠并自动填充每一列,直到填满为止。这种布局方式常见于图片展示、商品列表等场景,能够有效利用屏幕空间,提高视觉效果和用户体验。
以下是一个简单的PHP瀑布流分页示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>瀑布流分页</title>
<style>
.container {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.item {
width: calc(25% - 10px);
margin-bottom: 20px;
box-sizing: border-box;
border: 1px solid #ccc;
padding: 10px;
}
</style>
</head>
<body>
<div class="container" id="container">
<!-- 内容将通过JavaScript动态加载 -->
</div>
<button id="loadMore">加载更多</button>
<script>
let currentPage = 1;
const container = document.getElementById('container');
const loadMoreButton = document.getElementById('loadMore');
loadMoreButton.addEventListener('click', () => {
fetch(`/getItems?page=${currentPage}`)
.then(response => response.json())
.then(data => {
data.forEach(item => {
const div = document.createElement('div');
div.className = 'item';
div.textContent = item.title;
container.appendChild(div);
});
currentPage++;
});
});
// 初始加载
fetch(`/getItems?page=${currentPage}`)
.then(response => response.json())
.then(data => {
data.forEach(item => {
const div = document.createElement('div');
div.className = 'item';
div.textContent = item.title;
container.appendChild(div);
});
currentPage++;
});
</script>
</body>
</html>
<?php
// 假设我们有一个数据库连接
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$limit = 10; // 每页显示10条数据
$offset = ($page - 1) * $limit;
$stmt = $pdo->prepare("SELECT * FROM items LIMIT :limit OFFSET :offset");
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json');
echo json_encode($items);
}
?>
通过以上方法,你可以实现一个简单的PHP瀑布流分页功能,并解决可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云