Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
转场
Svelte高阶
响应式进阶
内容复用
动画
高级绑定
高级转场
上下文API
特殊元素
脚本模块
接下来
SvelteKit基础
介绍
路由
加载数据
Headers和cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

默认情况下转场只在它所绑定的Dom元素被添加或销毁时执行。就像当前的示例:切换显示隐藏整个列表并不触发绑定在列表项上的转场。 如果想在选中和取消副本框时也触发转场效果,而不只是通过滑动条添加或删除列表项时才触发。我们可以使用 global(全局) 转场:

Ordinarily, transitions will only play on elements when their direct containing block is added or destroyed. In the example here, toggling the visibility of the entire list does not apply transitions to individual list elements. Instead, we’d like transitions to not only play when individual items are added and removed with the slider but also when we toggle the checkbox. We can achieve this with a global transition, which plays when any block containing the transitions is added or removed:

App
<div transition:slide|global>
	{item}
</div>

在Svelte 3的时候, 转场默认都是全局的,如果只在绑定元素被添加或销毁时才触发可以使用|local. 让我想起了那个男主的台词:三十年河东,三十年河西,莫欺骚年穷啊。

In Svelte 3, transitions were global by default and you had to use the |local modifier to make them local.

Edit this page on GitHub

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
<script>
	import { slide } from 'svelte/transition';
 
	let items = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
 
	let showItems = $state(true);
	let i = $state(5);
</script>
 
<label>
	<input type="checkbox" bind:checked={showItems} />
	show list
</label>
 
<label>
	<input type="range" bind:value={i} max="10" />
</label>
 
{#if showItems}
	{#each items.slice(0, i) as item}
		<div transition:slide>
			{item}
		</div>
	{/each}
{/if}
 
<style>
	div {
		padding: 0.5em 0;
		border-top: 1px solid #eee;
	}
</style>