Svelte Tweened

2023-02-21 17:02 更新

設置數(shù)值并觀察DOM的自動更新是很酷的。知道更酷的是什么嗎?變化這些值。Svelte包括一些工具,可以幫助你建立靈活的用戶界面,使用動畫來傳達變化。

讓我們先把 ?progress?存儲改成一個?Tweened?值。

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

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

單擊這些按鈕會使進度條以動畫方式顯示其新值。雖然它有點機械化并且不令人滿意。我們需要添加一個easing(緩動)函數(shù):

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

	const progress = tweened(0, {
		duration: 400,
		easing: cubicOut
	});
</script>

svelte/easing? 模塊包含 Penner 緩動方程,或者您可以提供自己的 ?p => t? 函數(shù),其中 ?p? 和 ?t? 都是介于 0 和 1 之間的值。

可用于?tweened?的全部選項。

  • ?delay? — tween 開始前的毫秒數(shù)
  • ?duration? — 以毫秒為單位的 tween 持續(xù)時間,或者一個?(from,to)=> milliseconds?的函數(shù),允許你(例如)為更大的值變化指定更長的 tweens。
  • ?easing? — 一個 ?p => t? 函數(shù)
  • ?interpolate? — 一個自定義 ?(from, to) => t => value? 用于在任意值之間進行插值的函數(shù)。默認情況下,Svelte 將在數(shù)字、日期和形狀相同的數(shù)組和對象之間進行插值(只要它們只包含數(shù)字和日期或其他有效的數(shù)組和對象)。如果要插入(例如)顏色字符串或轉(zhuǎn)換矩陣,請?zhí)峁┳远x插值器

您還可以將這些選項作為第二個參數(shù)傳遞給 ?progress.set? 和 ?progress.update?,在這種情況下它們將覆蓋默認值。 ?set? 和 ?update? 方法都返回一個在 tween 完成時解析的 promise。

示例代碼

  • App.svelte

<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>


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號