首頁 >web前端 >css教學 >如何使用 CSS3 和 IntersectionObserver API 僅在元素位於視窗中時才對元素進行動畫處理?

如何使用 CSS3 和 IntersectionObserver API 僅在元素位於視窗中時才對元素進行動畫處理?

DDD
DDD原創
2024-11-15 11:59:02986瀏覽

How can I animate elements only when they are in the viewport using CSS3 and IntersectionObserver API?

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.

以上是如何使用 CSS3 和 IntersectionObserver API 僅在元素位於視窗中時才對元素進行動畫處理?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn