When using CSS animations on a web page, it's common to encounter situations where all animations play simultaneously, obscuring those at the bottom. To address this issue, we'll explore a solution using IntersectionObserver API.
The IntersectionObserver API allows developers to monitor changes in an element's intersection with its parent container or the viewport. When an element comes into view, it triggers an event that can be used to initiate actions.
Here's an example that triggers CSS class toggle when an element becomes visible in the viewport:
<br>const inViewport = (entries, observer) => {<br> entries.forEach(entry => {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">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 above example, all elements with the [data-inviewport] attribute will be monitored. When an element is in view, the is-inViewport class is added, and the animation defined in the CSS below will trigger.
<br>[data-inviewport="scale-in"] { <br> transition: 2s;<br> transform: scale(0.1);<br>}<br>[data-inviewport="scale-in"].is-inViewport { <br> transform: scale(1);<br>}</p> <p>[data-inviewport="fade-rotate"] { <br> transition: 2s;<br> opacity: 0;<br>}<br>[data-inviewport="fade-rotate"].is-inViewport { <br> transform: rotate(180deg);<br> opacity: 1;<br>}<br>
This solution ensures that animations only play when elements become visible during scrolling, improving the user experience and creating a more visually appealing web page.
The above is the detailed content of How to Trigger CSS Animations When Elements Enter the Viewport During Page Scroll?. For more information, please follow other related articles on the PHP Chinese website!