When incorporating CSS3 animations into web pages, users may encounter challenges when the animations are triggered prematurely or not visible in the viewport. To address this issue, the IntersectionObserver API provides a solution that allows elements to be animated only when they enter the user's viewport.
The IntersectionObserver API enables developers to observe changes in the intersection of target elements with an ancestor element or the document viewport. This API provides a callback function invoked when the target element becomes visible or invisible.
To implement this functionality:
const inViewport = (entries, observer) => { entries.forEach(entry => { entry.target.classList.toggle("is-inViewport", entry.isIntersecting); }); }; const observer = new IntersectionObserver(inViewport);
document.querySelectorAll('[data-inviewport]').forEach(el => { observer.observe(el, obsOptions); });
[data-inviewport="fade-in"] { transition: 2s; opacity: 0; } [data-inviewport="fade-in"].is-inViewport { opacity: 1; }
By following these steps, animations can be triggered dynamically based on an element's visibility in the viewport, providing a more intuitive and engaging user experience during page scrolling.
The above is the detailed content of How Can IntersectionObserver Enhance CSS3 Animations on Page Scroll?. For more information, please follow other related articles on the PHP Chinese website!