Hjquery实现滚动加载下一页+瀑布流布局
下面是一个简单的实现 H5 和 jQuery 实现滚动加载下一页和瀑布流布局的示例代码:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Infinite Scroll and Masonry Layout</title>
<style>
.grid-item {
break-inside: avoid;
padding: 10px;
border: 1px solid #ddd;
box-sizing: border-box;
margin-bottom: 10px;
}
.grid-sizer {
width: 32%;
}
.item-content {
height: 100px;
background-color: #f3f3f3;
border-radius: 4px;
text-align: center;
line-height: 100px;
}
</style>
</head>
<body>
<div id="content">
<!-- Items will be added here -->
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.min.js"></script>
<script>
$(document).ready(function() {
var $container = $('#content');
var page = 1;
var hasMore = true;
// Initialize Masonry after all images have loaded
$container.imagesLoaded(function() {
$container.masonry({
itemSelector: '.grid-item',
columnWidth: '.grid-sizer'
});
});
// Infinite scroll
$container.infinitescroll({
navSelector: '#page-nav', // selector for the paged navigation
nextSelector: '#page-nav a', // selector for the NEXT link (to page 2)
itemSelector: '.grid-item', // selector for all items you'll retrieve
pixelsFromNavToBottom: 50,
bufferPixels: 500,
errorCallback: function() {
hasMore = false;
}
},
// Callback that handles new items
function(newItems) {
var $newItems = $(newItems).css({ opacity: 0 });
$newItems.imagesLoaded(function() {
// Appends new items to the container
$newItems.appendTo($container);
// Animates new items
$newItems.animate({ opacity: 1 });
// Layout Masonry after new items are appended
$container.masonry('appended', $newItems);
page++;
if (!hasMore) {
$('#page-nav').remove(); // Disable infinitescroll if there's no more pages
}
});
});
// Replace 'url-to-your-api' with your server-side script
function fetchNewItems(page) {
$.ajax({
url: 'url-to-your-api?page=' + page,
type: 'GET',
dataType: 'json',
success: function(data) {
var html = '';
$.each(data.items, function(index, item) {
评论已关闭