js实现滚动加载,自动向后台请求分页数据,全部数据请求完毕后,不能再向下滚动,也不再重复请求。
注:后台用json-server模拟数据,数据格式如下
{
"data": [
{
"title": "1"
},
{
"title": "2"
},
{
"title": "3"
},
{
"title": "4"
},
{
"title": "5"
},
{
"title": "6"
},
{
"title": "7"
},
{
"title": "8"
},
{
"title": "9"
},
{
"title": "10"
},
{
"title": "11"
},
{
"title": "12"
}
]
}
前台代码:
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
margin: 0;
}
.content {
height: 200px;
}
.one {
background-color: red;
}
.two {
background-color: blue;
}
.there {
background-color: black;
}
.four {
background-color: cadetblue;
}
.five{
background-color: aqua;
}
.noActive{
display: none;
}
.active{
display: block;
}
</style>
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="main">
<div class="content one"></div>
<div class="content two"></div>
<div class="content there"></div>
<div class="content four"></div>
</div>
<img src="./loading.gif" alt="" id="load" class="a">
</body>
<script>
//每页数据开始索引
let start = 0
//每页显示条数
let limit = 10
//判断是否向后台请求数据,当请求回来的数据条数小于limit时,表示数据不足显示一页,
// 此时就不再向后台请求数据了,防止滚动条向上又向下重新请求数据
let flag=true
window.addEventListener('scroll', function() {
//浏览器视口的高度
const clientHeight = document.body.clientHeight;
//获取页面顶部被卷起来的高度
const scrollTop = document.body.scrollTop;
//获取页面文档的高度
const scrollHeight = document.documentElement.scrollHeight;
if(scrollTop+clientHeight == scrollHeight){
document.getElementById("load").setAttribute("class","active")
if(flag){
$.ajax({
url:`http://localhost:3000/data?_start=${start}&_limit=${limit}`,
type:"GET",
success:function (data) {
start = start+data.length
if(data.length<limit){
flag=false
}
const fragment = document.createDocumentFragment();
for(var i=0;i<data.length;i++){
const eleOne = document.createElement('div');
eleOne.setAttribute('class', 'content five');
eleOne.innerText=data[i].title
fragment.append(eleOne);
}
document.querySelector('.main').appendChild(fragment);
document.getElementById("load").setAttribute("class","noActive");
}
})
}
}
document.getElementById("load").setAttribute("class","noActive");
}, false);
</script>
</html>

该博客详细介绍了如何利用JavaScript实现页面滚动时自动从后台(如json-server)加载分页数据。当所有数据加载完毕后,滚动到底部将不再触发新的请求,避免重复加载。
1662

被折叠的 条评论
为什么被折叠?



