MST
星途 面试题库

面试题:Svelte动画过渡函数的综合应用

假设有一个列表,当用户点击某个列表项时,该项需要以`slide`过渡效果滑出列表,同时列表中的其他项需要以`fly`过渡效果调整位置来填补空缺。请用Svelte代码实现该功能,并解释在实现过程中如何管理动画的状态和顺序。
36.4万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

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>

动画状态和顺序管理解释

  1. 动画状态管理
    • 使用 removingIndex 变量来记录正在被移除的列表项的索引。当用户点击某个列表项的移除按钮时,removingIndex 被设置为该项的索引,这触发了相应的动画。
    • 当动画完成后(通过 setTimeout 模拟动画完成时间),从 items 数组中移除该项,并将 removingIndex 重置为 null
  2. 动画顺序管理
    • 对于被移除的项,通过 slideOut 动画使其滑出列表。
    • 对于其他需要填补空缺的项,使用 flyIn 动画。为了让它们有顺序地出现,根据 removingIndex 和当前项的索引来设置 animation-delay
    • 如果当前项的索引小于 removingIndex,则延迟时间为当前索引乘以一个固定值(这里是 100ms)。如果当前项的索引大于 removingIndex,则延迟时间为当前索引减 1 乘以固定值。这样确保了列表项依次以 fly 效果填补空缺。