前言
今天想说一下在平时写页面的时候遇到的
在我们写页面的时候经常会碰到一个业务场景就是需要监视一个dom元素是否在屏幕的可见区域出现,在以前我们可能会使用window.addEventLinstener绑定scroll事件来判断
但是现在window内置对象intersectionObserver可以来帮助我们判断该元素是否出现在 可见区域内,废话少说,我们直接上代码。
怎么使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>IntersectionObserver</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
.box1{
width: 100vw;
height: 100vh;
background-color: #FFE211;
}
.box2{
width: 100vw;
height: 100vh;
background-color: #39C5BB;
}
</style>
<body>
<div class="box1"></div>
<div class="box2"></div>
<script>
const box1 = document.querySelector(".box1")
const io = new IntersectionObserver((mutations) => {
const box1Status = mutations[0].isIntersecting
console.log("box1Status",box1Status);
});
io.observe(box1)
</script>
</body>
</html>
程序运行结果如下:
可以看到在随着我们鼠标滚动的同时,随着box1在不断地在页面中出现与消失,回调函数也在不断的触发,这样我们就可以在回调函数中判断元素状态然后实现对应逻辑,来完成对应的动画效果。
总结
在开发过程中,我们可以使用intersectionObserver来代替监听滚动事件来实现对元素出现到页面窗口的动画,该api的更多内容可以阅读关于该api的mdn文档