在上一章节中,我们使用延迟过渡来创建元素从一个待办事项列表移动到另一个列表时的动态效果。
为了完成这个动态效果,我们还需要对那些没有进行过渡的元素添加运动效果。为此,我们使用 animate 指令。
首先,从 svelte/animate 导入 flip 函数 — flip 代表 ‘First, Last, Invert, Play’(首次、最后、反转、播放)— 到 TodoList.svelte 中:
TodoList
<script>
import { flip } from 'svelte/animate';
import { send, receive } from './transition.js';
let { todos, remove } = $props();
</script><script lang="ts">
import { flip } from 'svelte/animate';
import { send, receive } from './transition.js';
let { todos, remove } = $props();
</script>然后将它添加到 <li> 元素中:
TodoList
<li
class={{ done: todo.done }}
in:receive={{ key: todo.id }}
out:send={{ key: todo.id }}
animate:flip
>在这种情况下,移动效果有点慢,所以我们可以添加一个 duration 参数:
TodoList
<li
class={{ done: todo.done }}
in:receive={{ key: todo.id }}
out:send={{ key: todo.id }}
animate:flip={{ duration: 200 }}
>
duration也可以是一个d => 毫秒的函数,其中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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<script>
import TodoList from './TodoList.svelte';
const todos = $state([
{ done: false, description: 'write some docs' }, { done: false, description: 'start writing blog post' }, { done: true, description: 'buy some milk' }, { done: false, description: 'mow the lawn' }, { done: false, description: 'feed the turtle' }, { done: false, description: 'fix some bugs' }]);
function remove(todo) {const index = todos.indexOf(todo);
todos.splice(index, 1);
}
</script>
<div class="board">
<input
placeholder="what needs to be done?"
onkeydown={(e) => {if (e.key !== 'Enter') return;
todos.push({done: false,
description: e.currentTarget.value
});
e.currentTarget.value = '';
}}
/>
<div class="todo">
<h2>todo</h2>
<TodoList todos={todos.filter((t) => !t.done)} {remove} /></div>
<div class="done">
<h2>done</h2>
<TodoList todos={todos.filter((t) => t.done)} {remove} /></div>
</div>
<style>
.board {display: grid;
grid-template-columns: 1fr 1fr;
grid-column-gap: 1em;
max-width: 36em;
margin: 0 auto;
}
.board > input {font-size: 1.4em;
grid-column: 1/3;
padding: 0.5em;
margin: 0 0 1rem 0;
}
h2 {font-size: 2em;
font-weight: 200;
}
</style>