本文标题:《「代码片段」当网页元素可见时……》。

镜像链接:https://www.wdssmq.com/post/20190701815.html

当元素滚动到可视区域时执行指定操作,比如应用 Animate.css 动画效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 原生 JS 选择器
function query(selector) {
return Array.from(document.querySelectorAll(selector));
}
// 使用构造函数创建对象并指定回调函数
const observer = new IntersectionObserver(function (changes) {
// 回调参数是数组,成员为 IntersectionObserverEntry 对象
changes.forEach(function (change) {
const container = change.target;
// console.log(change.intersectionRatio);
// 大于 0 时表示可见
if (change.intersectionRatio > 0) {
// console.log(container);
container.classList.add("flip", "animated");
} else {
container.classList.remove("flip", "animated");
}
});
});
// observe 方法用于对指定一个元素开启监听
query(".section-top img").forEach(function (item) {
// console.log(item);
observer.observe(item);
});

「- -」「- -」「- -」「- -」

IntersectionObserver API 使用教程 - 阮一峰的网络日志

http://www.ruanyifeng.com/blog/2016/11/intersectionobserver_api.html

Animate.css

https://daneden.github.io/animate.css/