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

這是我們在形式可訪問性上進行的小型系列中的第三篇文章。如果您錯過了第二篇文章,請查看“以:focus-visible的管理用戶焦點”。在

CSS盒子陰影和輪廓屬性獲得了主題。讓我們查看一些在真實主題中起作用的示例,以及我們必須將這些樣式應用於WordPress塊和元素的選項。

Svelte Transition API提供了一種使組件輸入或離開文檔(包括自定義Svelte Transitions)時動畫組件的方法。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Dreamweaver Mac版
視覺化網頁開發工具