交叉观察器IntersectionObserver最简单demo
IntersectionObserver内部使用getBoundingClientRect与requestIdleCallback实现
接近与离开0.5都会执行,去除接近0.5的执行
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body {
margin: 0px;
padding-top: 2000px;
}
#area {
background-color: #aaa;
height: 400px;
}
</style>
</head>
<body>
<div id="area">IntersectionObserver区域</div>
<script>
let observer = new IntersectionObserver(
(changes) => {
changes.forEach((change) => {
if (change.intersectionRatio < 0.5) return; //接近与离开0.5都会执行,去除接近0.5的执行
console.log(`ratio`, change.intersectionRatio);
});
},
{ threshold: 0.5 }
);
observer.observe(window.area);
</script>
</body>
</html>

浙公网安备 33010602011771号