通常,只有在添加或销毁元素的直接包含块时,过渡才会在元素上播放。在此处的示例中,切换整个列表的可见性不会将转换应用于单个列表元素。
¥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:
<div transition:slide|global>
{item}
</div>
在 Svelte 3 中,转换默认是全局的,你必须使用
|local
修饰符才能将其变为本地的。¥[!NOTE] In Svelte 3, transitions were global by default and you had to use the
|local
modifier to make them local.
<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>