Skip to main content

Svelte 转换引擎的一个特别强大的功能是能够推迟转换,以便它们可以在多个元素之间进行协调。

A particularly powerful feature of Svelte's transition engine is the ability to defer transitions, so that they can be coordinated between multiple elements.

以这对待办事项列表为例,其中切换待办事项会将其发送到相反的列表。 在现实世界中,对象的行为并非如此 — 它们不是消失并重新出现在另一个地方,而是经过一系列中间位置。 使用动作可以大大帮助用户了解应用中发生的情况。

Take this pair of todo lists, in which toggling a todo sends it to the opposite list. In the real world, objects don't behave like that — instead of disappearing and reappearing in another place, they move through a series of intermediate positions. Using motion can go a long way towards helping users understand what's happening in your app.

我们可以使用 crossfade 函数来实现此效果,该函数创建一对名为 sendreceive 的转换。 当一个元素是 'sent' 时,它会查找对应的 'received' 元素,并生成一个转换,将该元素转换到其对应元素的位置并将其淡出。 当元素为 'received' 时,情况相反。 如果没有对应的,则使用 fallback 转换。

We can achieve this effect using the crossfade function, which creates a pair of transitions called send and receive. When an element is 'sent', it looks for a corresponding element being 'received', and generates a transition that transforms the element to its counterpart's position and fades it out. When an element is 'received', the reverse happens. If there is no counterpart, the fallback transition is used.

找到第 65 行的 <label> 元素,并添加 sendreceive 转换:

Find the <label> element on line 65, and add the send and receive transitions:

<label
	in:receive="{{key: todo.id}}"
	out:send="{{key: todo.id}}"
>

对下一个 <label> 元素执行相同操作:

Do the same for the next <label> element:

<label
	class="done"
	in:receive="{{key: todo.id}}"
	out:send="{{key: todo.id}}"
>

现在,当你切换项目时,它们会顺利移动到新位置。 非转场项目仍然笨拙地跳跃 — 我们可以在下一章解决这个问题。

Now, when you toggle items, they move smoothly to their new location. The non-transitioning items still jump around awkwardly — we can fix that in the next chapter.