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

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

DDD
發布: 2024-11-15 11:59:02
原創
988 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板