स्टैगर ऐनिमेशन बनाना

वेब की सुविधाएं: sibling-count() और sibling-index()

स्टैगर ऐनिमेशन से एक दिलचस्प इफ़ेक्ट मिलता है. इसमें क्रम में लगाए गए कई एलिमेंट, एक साथ ऐनिमेट होने के बजाय, एक-एक करके ऐनिमेट होते हैं. हर एलिमेंट के ऐनिमेट होने के बीच थोड़ा सा समय लगता है. इस तकनीक का इस्तेमाल अक्सर सूचियों, गैलरी या नेविगेशन मेन्यू में किया जाता है, ताकि उपयोगकर्ता का ध्यान खींचा जा सके. साथ ही, इंटरैक्शन को बेहतर और दिलचस्प बनाया जा सके.

sibling-index() की मदद से, ऐनिमेशन को स्टैगर करना

animation-delay प्रॉपर्टी पर sibling-index() प्रॉपर्टी का इस्तेमाल करें, ताकि हर एलिमेंट पर ऐनिमेशन को पैरंट में उनकी पोज़िशन के अनुपात में ऑफ़सेट किया जा सके. sibling-index() फ़ंक्शन एक पूर्णांक दिखाता है. इसलिए, इसे समय में बदलने के लिए, समय की इकाई से गुणा करना होगा.

#stagger-list > .item {
  --stagger-time: 0.1s;
  /* Define the animation first */
  animation: fade-in 0.4s;
  /* Set the `animation-delay` to a time multiplied by the `sibling-index()` */
  animation-delay: calc(sibling-index() * var(--stagger-time))
}

ज़रूरी: उपयोगकर्ता की प्राथमिकताओं का सम्मान करें. इसके लिए, उन उपयोगकर्ताओं के लिए ऐनिमेशन बंद करें जो कम मोशन पसंद करते हैं.

@media (prefers-reduced-motion: reduce){
  /* Disable animation for users who prefer reduced motion. */
  #stagger-list > .item {
    animation: none;
  }
}

फ़ॉलबैक रणनीतियां

sibling-index() के लिए सहायता की जांच करें. इसके लिए, @supports (animation-delay: calc(sibling-index() * 0.1s)){} के साथ सीएसएस या !CSS.supports('animation-delay: calc(sibling-index() * 0.1s)') के साथ JavaScript का इस्तेमाल करें.

पुराने ब्राउज़र में स्टैगर ऐनिमेशन की सुविधा इस्तेमाल करने के लिए, JavaScript का इस्तेमाल करके हर सिबलिंग एलिमेंट में --sibling-index कस्टम प्रॉपर्टी जोड़ें. ज़रूरी: इसे CSS.supports('animation-delay: calc(sibling-index() * 0.1s)') टेस्ट में रैप करें, ताकि ग़ैर-ज़रूरी JavaScript को चलने से रोका जा सके.

if(!CSS.supports('animation-delay: calc(sibling-index() * 0.1s)')){
  const staggerList = document.getElementById('stagger-list');
  [...staggerList.children].forEach((el, index)=>el.style.setProperty('--sibling-index', index + 1));
}

--sibling-index कस्टम प्रॉपर्टी का इस्तेमाल करने वाला animation-delay डिक्लेरेशन जोड़ें. यह sibling-index() फ़ंक्शन का इस्तेमाल करने वाले animation-delay डिक्लेरेशन से पहले होना चाहिए. इसे @supports में रैप करने की ज़रूरत नहीं है - पुराने ब्राउज़र, दूसरे एलान को पार्स नहीं करेंगे और पहले एलान का इस्तेमाल करेंगे.

#stagger-list > .item {
  animation-delay: calc(var(--sibling-index) * var(--stagger-time));
  animation-delay: calc(sibling-index() * var(--stagger-time));
}