在 上一章 中,我们使用延迟过渡创建了一个列表元素从一个表移动到另一个表的运动效果。
要完成这个效果,我们还需要对剩下的 不 过渡的元素应用运动效果。要达到这一点,我们使用 animate
标志。
首先,在 TodoList.svelte
中,从 svelte/animate
导入 flip
函数,flip 代表 'First, Last, Invert, Play':
TodoList.svelte
<script>
import { flip } from 'svelte/animate';
import { send, receive } from './transition.js';
export let store;
export let done;
</script>
然后添加到 li
元素上:
TodoList.svelte
<li
class:done
in:receive={{ key: todo.id }}
out:send={{ key: todo.id }}
animate:flip
>
现在运动得有一点慢,我们可以加一个 duration
参数:
TodoList.svelte
<li
class:done
in:receive={{ key: todo.id }}
out:send={{ key: todo.id }}
animate:flip={{ duration: 200 }}
>
duration
也可以是一个d => milliseconds
函数,其中d
是元素要移动的像素个数
注意所有的过渡和动画都是由 CSS 完成的,而非 JavaScript,因此它们不会阻断主线程或者被主线程阻断。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<script>
import { send, receive } from './transition.js';
export let store;
export let done;
</script>
<ul class="todos">
{#each $store.filter((todo) => todo.done === done) as todo (todo.id)}
<li
class:done
in:receive={{ key: todo.id }}
out:send={{ key: todo.id }}
>
<label>
<input
type="checkbox"
checked={todo.done}
on:change={(e) => store.mark(todo, e.currentTarget.checked)}
/>
<span>{todo.description}</span>
<button on:click={() => store.remove(todo)} aria-label="Remove"></button>
</label>
</li>
{/each}
</ul>
<style>
label {
width: 100%;
height: 100%;
display: flex;
}
span {
flex: 1;
}
button {
background-image: url(./remove.svg);
}
</style>