Svelte 代码实现
<script>
let items = ['Item 1', 'Item 2', 'Item 3', 'Item 4'];
let removingIndex = null;
const removeItem = (index) => {
removingIndex = index;
setTimeout(() => {
items = items.filter((_, i) => i!== index);
removingIndex = null;
}, 300); // 300ms 是动画过渡时间,根据实际情况调整
};
</script>
{#each items as item, index}
{#if removingIndex === index}
<div style="position: relative;">
<div style="position: absolute; left: 0; top: 0; opacity: 1; animation: slideOut 300ms ease-out forwards;">
{item}
</div>
</div>
{:else}
<div style="animation: flyIn 300ms ease-out forwards; animation-delay: {removingIndex === null? 0 : (index < removingIndex? index * 100 : (index - 1) * 100)}ms;">
{item}
</div>
{/if}
<button on:click={() => removeItem(index)}>Remove {item}</button>
{/each}
<style>
@keyframes slideOut {
from {
transform: translateX(0);
}
to {
transform: translateX(100%);
opacity: 0;
}
}
@keyframes flyIn {
from {
transform: translateY(-20px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
</style>
动画状态和顺序管理解释
- 动画状态管理:
- 使用
removingIndex
变量来记录正在被移除的列表项的索引。当用户点击某个列表项的移除按钮时,removingIndex
被设置为该项的索引,这触发了相应的动画。
- 当动画完成后(通过
setTimeout
模拟动画完成时间),从 items
数组中移除该项,并将 removingIndex
重置为 null
。
- 动画顺序管理:
- 对于被移除的项,通过
slideOut
动画使其滑出列表。
- 对于其他需要填补空缺的项,使用
flyIn
动画。为了让它们有顺序地出现,根据 removingIndex
和当前项的索引来设置 animation-delay
。
- 如果当前项的索引小于
removingIndex
,则延迟时间为当前索引乘以一个固定值(这里是 100ms
)。如果当前项的索引大于 removingIndex
,则延迟时间为当前索引减 1 乘以固定值。这样确保了列表项依次以 fly
效果填补空缺。