animate:

  1. animate:name
  1. animate:name={params}
  1. animation = (node: HTMLElement, { from: DOMRect, to: DOMRect } , params: any) => {
  2. delay?: number,
  3. duration?: number,
  4. easing?: (t: number) => number,
  5. css?: (t: number, u: number) => string,
  6. tick?: (t: number, u: number) => void
  7. }
  1. DOMRect {
  2. bottom: number,
  3. height: number,
  4. ​​left: number,
  5. right: number,
  6. ​top: number,
  7. width: number,
  8. x: number,
  9. y:number
  10. }

当一个通过 each 生成的块发生重排的时候,Animation 才会执行。当元素被删除的时候动画不会执行,只有 each 的列表数据发生重排的时候才会执行 Animation 。且animate: 指令只能在each块的直接子元素上。

  1. <!-- When `list` is reordered the animation will run-->
  2. {#each list as item, index (item)}
  3. <li animate:flip>{item}</li>
  4. {/each}

animate 可以是内置的 animation 方法或自定义的 animation 方法。

Animation参数

Actions 还有 transitions 一样,Animation 也有参数。

  1. {#each list as item, index (item)}
  2. <li animate:flip="{{ delay: 500 }}">{item}</li>
  3. {/each}

双大括号 {{curlies}} 不是特殊的语法,只是一个在表达式标签中包含一个对象字面量

自定义Animation函数

  1. <script>
  2. import { cubicOut } from 'svelte/easing';
  3. function whizz(node, { from, to }, params) {
  4. const dx = from.left - to.left;
  5. const dy = from.top - to.top;
  6. const d = Math.sqrt(dx * dx + dy * dy);
  7. return {
  8. delay: 0,
  9. duration: Math.sqrt(d) * 120,
  10. easing: cubicOut,
  11. css: (t, u) =>
  12. `transform: translate(${u * dx}px, ${u * dy}px) rotate(${t*360}deg);`
  13. };
  14. }
  15. </script>
  16. {#each list as item, index (item)}
  17. <div animate:whizz>{item}</div>
  18. {/each}

Animations 可以是自定义的函数,函数的参数分别是 nodeanimation 对象、及一个任何格式的参数。animation 对象参数包含 fromto 属性,且都包含了能描述元素的物理几何位置 startend 的 DOMRect 属性。当列表数据发生重排,且 DOM 已经完成更新,from 属性表示的是元素在起始位置的 DOMRect,to 属性表示的是元素结束位置的 DOMRect。

如果返回的对象有 css 的方法,Svelte 会为这个元素创建并执行一个 css 的动画。

当缓动动画执行的时候,t0 变化到 1,且会被作为参数传入到css方法中,参数 u 等同于 1-t

在动画开始之前,animate 会被通过不同的参数 tu 反复的调用。

自定义的 animation 函数同样可以返回 tick 函数,在动画的执行过程中被调用,同样的也是以参数 tu

  1. <script>
  2. import { cubicOut } from 'svelte/easing';
  3. function whizz(node, { from, to }, params) {
  4. const dx = from.left - to.left;
  5. const dy = from.top - to.top;
  6. const d = Math.sqrt(dx * dx + dy * dy);
  7. return {
  8. delay: 0,
  9. duration: Math.sqrt(d) * 120,
  10. easing: cubicOut,
  11. tick: (t, u) =>
  12. Object.assign(node.style, {
  13. color: t > 0.5 ? 'Pink' : 'Blue'
  14. });
  15. };
  16. }
  17. </script>
  18. {#each list as item, index (item)}
  19. <div animate:whizz>{item}</div>
  20. {/each}

尽可能的使用 css 而不是 tick 函数,之所以这样做-是因为 css 动画可以在主线程上进行,防止在低端设备出现卡顿。