const elements = [ { elem: document.querySelector("#elemt"), observer: new IntersectionObserver(observerCallback), }, ]; // 定义回调函数 function observerCallback(entries) { entries.forEach((entry) => { // 如果元素进入视窗,执行动画 if (entry.isIntersecting) { entry.target.classList.add("animate"); } else { // 如果元素离开视窗,取消动画 entry.target.classList.remove("animate"); } }); }如何动画只执行一次
时间: 2024-02-14 18:16:47 浏览: 113
你可以在 `entry.target` 元素执行动画后,将该元素从观察列表中移除,这样就可以只执行一次动画。代码如下所示:
```javascript
const elements = [
{
elem: document.querySelector("#elemt"),
observer: new IntersectionObserver(observerCallback),
},
];
function observerCallback(entries, observer) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add("animate");
observer.unobserve(entry.target); // 移除观察列表中的元素
} else {
entry.target.classList.remove("animate");
}
});
}
```
在观察列表中移除元素的方法是调用 `observer.unobserve(entry.target)`,需要传入被观察的元素作为参数。这样,在该元素执行动画后,就不会再被观察到,动画也就只会执行一次。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)