Skip to main content

Svelte 过渡引擎的一个特别强大的特性是允许我们 延迟 过渡,因此在多个元素之间可以达到协调配合。

拿这两个待办列表为例,点击复选框就会把该项转移到另一个列表中。在现实世界中,物体并不是这样突然从一个地方消失又突然从另一个地方出现的,相反它们会经过一段连续的位置移动过去。使用运动效果可以大大帮助用户了解你的应用中发生了什么。

我们可以使用 transition.js 中的 crossfade 函数实现这点,该函数会创建两个叫 sendreceive 的过渡函数。当一个元素被发送的时候,它会找到那个与之相对的要被接收的元素,然后生成一段从自己的位置移动到对方位置的动画并渐渐消失。当一个元素被接收时,就反过来。如果没有找到对应的元素,就会调用 fallback 过渡。

打开 TodoList.svelte,首先从 transition.js 导入 sendreceive 两个过渡函数:

TodoList.svelte
<script>
	import { send, receive } from './transition.js';

	export let store;
	export let done;
</script>

然后把它们加入到 li 元素中,使用 todo.id 属性作为 key 来匹配元素:

TodoList.svelte
<li
	class:done
	in:receive={{ key: todo.id }}
	out:send={{ key: todo.id }}
>

现在,当你点击复选框时,列表元素会平滑地移动到新位置。剩下不移动的元素没有过渡效果,依然会很难看地跳来跳去,我们在下一章中解决这个问题。

Next: 动画

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
<script>
	import { createTodoStore } from './todos.js';
	import TodoList from './TodoList.svelte';
 
	const todos = createTodoStore([
		{ 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' }
	]);
</script>
 
<div class="board">
	<input
		placeholder="what needs to be done?"
		on:keydown={(e) => {
			if (e.key !== 'Enter') return;
 
			todos.add(e.currentTarget.value);
			e.currentTarget.value = '';
		}}
	/>
 
	<div class="todo">
		<h2>todo</h2>
		<TodoList store={todos} done={false} />
	</div>
 
	<div class="done">
		<h2>done</h2>
		<TodoList store={todos} done={true} />
	</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>
 
initialising