如何在水平布局中触发动画

How to trigger animations in horizontal layout

我想在水平布局中触发 CSS 动画,仅当动画元素进入视口时。我还想让它们在每次进入视口时都被触发,而不仅仅是一次。

JavaScript Intersection Observer API 可以观察任何滚动方向的元素位置,可以在它们 enter/leave 视口时对它们执行操作,并且可以在每次这些事件时重复这些操作发生。它非常高效且得到了很好的支持。这是一个基本示例:

// 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);
});