用 IntersectionObserver api 监听元素曝光
以前在 H5 页面都是监听 window 的 scroll 事件从而去监测元素的曝光。但是最近接到的一个需求,去监听 scroll 事件监测曝光并不友好,于是 发现了一个从没用过的 api ,试着做了一个demo ,由于不会监听scroll 事件去频繁触发 scroll 事件。所以性能上会提高很多,但是不兼容 ie, MDN 上有官方的说明 https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserver#%E7%A4%BA%E4%BE%8B。
下面附上demo代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
#box {
background-color: rgba(40, 40, 190, 255);
border: 4px solid rgb(20, 20, 120);
transition: background-color 1s, border 1s;
width: 100%;
height: 950px;
align-items: center;
justify-content: center;
padding: 20px 0;
}
.vertical {
color: white;
font: 32px "Arial";
margin: 10px;
width: 300px;
height: 196px;
margin: 0 auto;
border: 2px solid #ccc;
}
.extra {
width: 350px;
height: 350px;
margin-top: 10px;
border: 4px solid rgb(20, 20, 120);
text-align: center;
padding: 20px;
}
</style>
</head>
<body>
<div id="box">
<div class="vertical" data-id='1'>
1
</div>
<div class="vertical" data-id='2'>
2
</div>
<div class="vertical" data-id='3'>
3
</div>
<div class="vertical" data-id='4'>
4
</div>
<div class="vertical" data-id='5'>
5
</div>
</div>
</body>
<script>
var numSteps = 20.0;
var boxElement;
var ele = [];
var prevRatio = 0.5;
window.addEventListener("load", function (event) {
for (var i = 0; i < document.getElementsByClassName("vertical").length; i++) {
boxElement = document.getElementsByClassName("vertical")[i];
createObserver();
}
}, false);
function createObserver() {
var observer;
var options = {
root: null, // null 为相对于视窗,也可为具体要监测的某个祖先元素
rootMargin: "15px", // 距离祖先元素的 margin
threshold: buildThresholdList() // 可见的阀值
};
observer = new IntersectionObserver(handleIntersect, options);
observer.observe(boxElement);
}
function buildThresholdList() {
var thresholds = [];
var numSteps = 10;
for (var i = 1.0; i <= numSteps; i++) {
var ratio = i / numSteps;
thresholds.push(ratio);
}
thresholds.push(0);
return thresholds;
}
function handleIntersect(entries, observer) {
entries.forEach(function (entry, i) {
if (entry.intersectionRatio > prevRatio) {
if (ele.indexOf(entry.target.dataset.id) == -1) {
console.log("--曝光了--" + entry.target.dataset.id);
// 在这里可以做上报逻辑,曝光只需一次,在此做了限制
}
// ele = unique(ele);
ele.push(entry.target.dataset.id)
} else {
console.log("--看不见--" + entry.target.dataset.id);
}
});
}
function unique(arr) {
if (!Array.isArray(arr)) {
console.log('type error!')
return
}
var res = []
for (var i = 0; i < arr.length; i++) {
if (res.indexOf(arr[i]) === -1) {
res.push(arr[i])
}
}
return res;
}
</script>
</html>