אנימציות גלילה: animation-timeline במקום IntersectionObserver
אנימציות גלילה: animation-timeline במקום IntersectionObserver
Scroll-driven animations חותך את הבעיה מהשורש. זו אותה CSS animation שאתה כבר מכיר, עם תחליף אחד: במקום שזמן מניע את ההתקדמות, מיקום container הגלילה עושה זאת. הדפדפן יכול להריץ אותו על ה-compositor.
סרגל התקדמות בארבעה שורות
css
.progress {position: fixed;inset: 0 0 auto 0;height: 4px;transform-origin: left;animation: grow linear both;animation-timeline: scroll(root block);}@keyframes grow {from { transform: scaleX(0); }to { transform: scaleX(1); }}
גילוי בגלילה: ציר הזמן view()
css
.reveal {animation: fade-up linear both;animation-timeline: view();animation-range: entry 0% entry 60%;}@keyframes fade-up {from { opacity: 0; transform: translateY(32px); }to { opacity: 1; transform: translateY(0); }}
ארבעת הטווחים בשם: entry، exit، cover (ברירת מחדל), contain.
המלכודת שעולה שעה: קיצור animation מאפס את ציר הזמן
css
/* שבור: הקיצור מאפס animation-timeline ל-auto */.reveal {animation-timeline: view();animation-range: entry 0% entry 60%;animation: fade-up linear both;}
css
/* נכון: ציר זמן וטווח אחרי הקיצור */.reveal {animation: fade-up linear both;animation-timeline: view();animation-range: entry 0% entry 60%;}
ציירי זמן עם שם
css
.gallery {overflow-x: auto;scroll-timeline: --gallery inline;}.gallery-indicator {animation: fill linear both;animation-timeline: --gallery;timeline-scope: --gallery;}
שיפור מדורג אינו אופציונלי כאן
css
.reveal {opacity: 1;}@supports (animation-timeline: view()) {@media (prefers-reduced-motion: no-preference) {.reveal {animation: fade-up linear both;animation-timeline: view();animation-range: entry 0% entry 60%;}}}
מלכודות ושיטות עבודה מומלצות
- אנים רק
transformו-opacity. - לעולם אל תסתיר תוכן שרק אנימציה יכולה לחשוף.
- "למה האנימציה שלי עומדת?" זה כמעט תמיד container הגלילה.
- השתמש ב-
bothכ-fill mode. - תנועה מופחתת היא הגדרה רפואית, לא נימוס.
- אל תמחק JavaScript שאתה עדיין צריך.
סיכום
Scroll-driven animations מיישם את אותו הרעיון לגבי ה-thread הראשי על קטגוריה שלמה של אפקטים: מה שדרש מאזין גלילה, observer וחלפן מחלקות הופך למאפיין CSS אחד.