交叉观察器(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>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
#el {
transition: all 0.5s;
}
div {
width: 1000px;
background-color: cornsilk;
}
.s {
transition: all 0.5s;
width: 400px;
height: 200px;
background-color: rgb(77, 212, 212);
margin-bottom: 100px;
display: inline-block;
}
</style>
</head>
<body>
<div id="el">
<p class="s"></p>
<p class="s"></p>
<p class="s"></p>
<p class="s"></p>
<p class="s"></p>
<p class="s"></p>
<p class="s"></p>
<p class="s"></p>
<p class="s"></p>
<p class="s"></p>
<p class="s"></p>
<p class="s"></p>
<p class="s"></p>
<p class="s"></p>
<p class="s"></p>
<p class="s"></p>
<p class="s"></p>
</div>
</body>
<script>
const io = new IntersectionObserver(
(entrys) => {
entrys.forEach((is) => {
if (is.isIntersecting) {
setTimeout(() => {
is.target.style.backgroundColor = "blue";
is.target.style.transform = "rotate(360deg)";
}, 1000);
io.unobserve(is.target);
}
});
},
{
rootMargin: "0px 0px 50px 0px",
}
);
Array.from(document.getElementsByClassName("s")).forEach((item) => {
io.observe(item);
});
</script>
</html>