我想要在水平布局中触发CSS动画,仅当动画元素进入视口时。我也希望它们每次进入视口时都被触发,而不是只触发一次。
发布于 2020-12-31 12:48:58
JavaScript Intersection Observer API可以监视元素在任何滚动方向上的位置,可以在元素进入/离开视口时对它们执行操作,并且可以在每次发生这些事件时重复这些操作。它非常高效并且得到了很好的支持。下面是一个基本的例子:
// Get an array of elements to watch
let elements = document.querySelectorAll('.foo');
// Set an observer to watch their position relative to the viewport boundaries
let observer = new IntersectionObserver(function (entries, self) {
entries.forEach(entry => {
// If this item is in the viewport
if (entry.isIntersecting) {
// Do some code on that item
entry.target.classList.toggle('animated');
}
});
}, { rootMargin: '0px 0px 0px 0px' });
// Tell each element to be watched
elements.forEach(el => {
observer.observe(el);
});https://stackoverflow.com/questions/65515564
复制相似问题