【发布时间】:2020-12-31 01:18:36
【问题描述】:
我想在水平布局中触发 CSS 动画,只有当动画元素进入视口时。我还想让它们在每次进入视口时触发,而不仅仅是一次。
【问题讨论】:
标签: javascript css-animations horizontal-scrolling
我想在水平布局中触发 CSS 动画,只有当动画元素进入视口时。我还想让它们在每次进入视口时触发,而不仅仅是一次。
【问题讨论】:
标签: javascript css-animations horizontal-scrolling
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);
});
【讨论】: