第十一屆鐵人賽 前端工程師的另一個選擇 svelte DAY21- 動態 tweened

Motion Tweened

Motion Tweened 是今天要分享的內容,在分享完store之後另一個進階的 svelte的內容就是 motion,而第一個要分享給大家的motionn就是今天要分享的tweened。

Tweened 是甚麼

所謂的 Tweened 把動態之間的部分用內插法把動態補齊,簡單講就是看起動態不會有跳格的現象,所以在實作 Tweened 之前先來做一個不是用 Tweened 的 Progress Bar,請看以下內容。

<script>
    import { writable } from 'svelte/store';

    const progress = writable(0);
</script>

<style>
    progress {
        display: block;
        width: 100%;
    }
</style>

<progress value={$progress}></progress>

<button on:click="{() => progress.set(0)}">
    0%
</button>

<button on:click="{() => progress.set(0.25)}">
    25%
</button>

<button on:click="{() => progress.set(0.5)}">
    50%
</button>

<button on:click="{() => progress.set(0.75)}">
    75%
</button>

<button on:click="{() => progress.set(1)}">
    100%
</button>

這是一個很簡單的Progress Bar的例子,當運作起來讀者可以看到直接點及按鈕所造成的結果就是直接跑到指定的進度,接下來我們將要實作Tweened版本的 Progress Bar。

實作 Tweened 版本的 Progress Bar

實作其實很簡單,大家可以先看一下下面的程式碼。

<script>
    import { tweened } from 'svelte/motion';

    const progress = tweened(0);
</script>

<style>
    progress {
        display: block;
        width: 100%;
    }
</style>

<progress value={$progress}></progress>

<button on:click="{() => progress.set(0)}">
    0%
</button>

<button on:click="{() => progress.set(0.25)}">
    25%
</button>

<button on:click="{() => progress.set(0.5)}">
    50%
</button>

<button on:click="{() => progress.set(0.75)}">
    75%
</button>

<button on:click="{() => progress.set(1)}">
    100%
</button>

其實簡單講也沒有修改甚麼,就是把之前的writable用tweened給取代掉而已,這邊要注意的是使用tweened要先重svelte/motion內import tweened進來。

小結

今天的內容很簡單,就是透過import svelte/motion中的tweened就可以完成一個動態內差的 Progress Bar,所以說 svelte是不是很方便呢。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *