准备工作:了解如何获取浏览器各种高度
一. 下拉加载的简单实现
1. 获取网页被卷去的高度
document.documentElement.scrollTop
2. 获取可视区域高度
document.documentElement.clientHeight
3. 获取整个文档高度
document.body.scrollHeight
4. 判断是否需要加载
当 卷去高度 + 可视区域 + 加载参数 > 整个文档高度
时加载更多,其中加载参数默认为0,也就是滚动条拉到最下面才判断为可加载。
5. 监听滚动条事件
function load(range=0){
let scroll = document.documentElement.scrollTop;
let view = document.documentElement.clientHeight;
let all = document.body.scrollHeight;
if(scroll + view + range > all){
return true
}
return false;
}
- 测试:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>下拉加载更多</title>
<style>
div{
height:2000px;
}
</style>
</head>
<body>
<div></div>
<script>
function load(range=0){
let scroll = document.documentElement.scrollTop;
let view = document.documentElement.clientHeight;
let all = document.body.scrollHeight;
if(scroll + view + range > all){
return true
}
return false;
}
window.onscroll = function(){
console.log(load())
}
</script>
</body>
</html>
![](https://img.haomeiwen.com/i19383585/e67246e94351bc5b.png)
可以看到,当下拉到最下面时的确判定为可加载,但是多次触发加载可能会出问题(请求数据没那么快),而且重复加载可能卡死。
6. 优化(添加防抖)
<script>
function load(range=0){
let scroll = document.documentElement.scrollTop;
let view = document.documentElement.clientHeight;
let all = document.body.scrollHeight;
if(scroll + view + range > all){
console.log('开始加载');
}
console.log('等一会');
}
function debounce(fn,delay){
var timer = null;
return function(){
if(timer){
clearTimeout(timer);
}
timer = setTimeout(fn,delay);
}
}
window.onscroll = debounce(load,500);
</script>
![](https://img.haomeiwen.com/i19383585/9677276b0f0446e0.png)
网友评论