当元素滚动到可视区域时执行指定操作,比如应用Animate.css动画效果
// 原生JS选择器 function query(selector) { return Array.from(document.querySelectorAll(selector)); } // 使用构造函数创建对象并指定回调函数 let observer = new IntersectionObserver( function (changes) { // 回调参数是数组,成员为IntersectionObserverEntry对象 changes.forEach(function (change) { let 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/