jQuery 上下翻页特效是一种使用 jQuery 库实现的页面内容动态加载和显示的效果。它通常用于在不刷新整个页面的情况下,通过滚动或点击按钮来加载和显示新的内容页。
以下是一个简单的 jQuery 无限滚动示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Infinite Scroll</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.content {
height: 200px;
overflow-y: scroll;
border: 1px solid #ccc;
}
.item {
padding: 10px;
border-bottom: 1px solid #eee;
}
</style>
</head>
<body>
<div class="content" id="content">
<!-- Content will be loaded here -->
</div>
<script>
$(document).ready(function() {
var page = 1;
var loading = false;
function loadContent(page) {
if (loading) return;
loading = true;
$.ajax({
url: 'load_content.php', // 假设这是后端接口
method: 'GET',
data: { page: page },
success: function(data) {
$('#content').append(data);
loading = false;
page++;
},
error: function() {
loading = false;
alert('Failed to load content');
}
});
}
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
loadContent(page);
}
});
loadContent(page); // 初始加载第一页内容
});
</script>
</body>
</html>
原因:可能是由于滚动事件触发过于频繁,导致多次请求。
解决方法:
function debounce(func, wait) {
var timeout;
return function() {
var context = this, args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function() {
func.apply(context, args);
}, wait);
};
}
$(window).scroll(debounce(function() {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
loadContent(page);
}
}, 200));
通过以上方法,可以有效解决无限滚动加载内容时的闪烁和重复加载问题。
领取专属 10元无门槛券
手把手带您无忧上云