常见场景: 滚动条滚动到底部时加载数据,如果监听滚动事件,会造成不必要的浪费。如频繁滚动但未达底部。可以建立观察者,监听loading标识元素到达视口某位置后再加载数据。
步骤
创建一个新的 IntersectionObserver 对象,当其监听到目标元素的可见部分(的比例)超过了一个或多个阈值(threshold)时,会执行指定的回调函数。
- 创建观察者:new IntersectionObserver(),接受两个参数
- 参数1:回调函数
参数entries为观察的所有元素的集合。被观察元素的isIntersecting属性为true时表示已超过重叠阈值。 - 参数2:构造器
root为与被观察元素重叠的元素,默认为null,表示顶级文档视口。thresholds表示阈值,小数表示百分比,即重叠比例,默认为0。
- 参数1:回调函数
- 观察元素:IntersectionObserver.observe(),一个观察者可以观察多个元素,当观察多个元素时,参数1中的entries也为多个。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scroll Loading</title>
<style>
.content {
height: 800px;
overflow-y: scroll;
padding: 20px;
border: 1px solid #333;
}
.box {
width: 100%;
height: 400px;
background-color: #bfd;
margin-bottom: 30px;
}
#loading {
display: block;
text-align: center;
padding: 10px;
background-color: #f1f1f1;
margin-top: 10px;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<div class="content">
<div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div>
<div id="loading" class="hidden">Loading...</div>
</div>
<script>
// 建立观察者
const loading = document.getElementById('loading');
let ob = new IntersectionObserver(function (entries) {
let loading = entries[0]
console.log(loading.isIntersecting);
if (loading.isIntersecting) {
console.log('加载更多');
}
}, {
thresholds: 0.5
})
ob.observe(loading);
</script>
</body>
</html>