Animate Elements in Viewport
In CSS3, you can add animations to HTML elements to make them move or change appearance when certain conditions are met. However, if you want these animations to only play when the elements are visible in the viewport, you can use the IntersectionObserver API.
Using IntersectionObserver API
The IntersectionObserver API allows you to observe the intersection of elements with the viewport or an ancestor element. When an element becomes visible (i.e., intersects the viewport), you can trigger an action, such as toggling a class or executing an animation.
Here's an example implementation using IntersectionObserver:
const inViewport = (entries, observer) => { entries.forEach(entry => { entry.target.classList.toggle("is-inViewport", entry.isIntersecting); }); }; const Obs = new IntersectionObserver(inViewport); const obsOptions = {}; //See: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#Intersection_observer_options // Attach observer to every [data-inviewport] element: document.querySelectorAll('[data-inviewport]').forEach(el => { Obs.observe(el, obsOptions); });
In the inViewport function, we check if the element is intersecting the viewport (i.e., entry.isIntersecting) and toggle a class is-inViewport on the target element.
To style the animation, you can use CSS transitions or keyframes as usual. For instance, you can define the animation for an element with data-inviewport="scale-in" as follows:
[data-inviewport="scale-in"] { transition: 2s; transform: scale(0.1); } [data-inviewport="scale-in"].is-inViewport { transform: scale(1); }
With this setup, the element will scale from 10% to 100% when it becomes visible in the viewport.
Das obige ist der detaillierte Inhalt vonWie kann ich mithilfe von CSS3 und der IntersectionObserver-API Elemente nur dann animieren, wenn sie sich im Ansichtsfenster befinden?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!