通常,传达值正在变化的一个好方法是使用动画。Svelte 提供了一些类来为你的用户界面添加动画效果。
从 svelte/motion 导入 Tween 类:
App
<script>
import { Tween } from 'svelte/motion';
let progress = $state(0);
</script><script lang="ts">
import { Tween } from 'svelte/motion';
let progress = $state(0);
</script>将 progress 转换为 Tween 的实例:
App
<script>
import { Tween } from 'svelte/motion';
let progress = new Tween(0);
</script><script lang="ts">
import { Tween } from 'svelte/motion';
let progress = new Tween(0);
</script>Tween 类有一个可写的 target 属性和一个只读的 current 属性 — 更新 <progress> 元素...
<progress value={progress.current}></progress>...以及每个事件处理程序:
<button onclick={() => (progress.target = 0)}>
0%
</button>点击按钮会使进度条动画过渡到新的值。不过这看起来有点机械和不令人满意。我们需要添加一个缓动函数:
App
<script>
import { Tween } from 'svelte/motion';
import { cubicOut } from 'svelte/easing';
let progress = new Tween(0, {
duration: 400,
easing: cubicOut
});
</script><script lang="ts">
import { Tween } from 'svelte/motion';
import { cubicOut } from 'svelte/easing';
let progress = new Tween(0, {
duration: 400,
easing: cubicOut
});
</script>
svelte/easing模块包含了 Penner 缓动方程,你也可以提供自己的p => t函数,其中p和t都是介于 0 和 1 之间的值。
Tween 可用的完整选项有:
delay— 补间动画开始前的毫秒数duration— 可以是补间动画持续时间的毫秒数,也可以是(from, to) => milliseconds函数,允许你(例如)为更大的值变化指定更长的补间时间easing— 一个p => t函数interpolate— 一个自定义的(from, to) => t => value函数,用于在任意值之间进行插值。默认情况下,Svelte 将在数字、日期和形状相同的数组和对象之间进行插值(只要它们只包含数字和日期或其他有效的数组和对象)。如果你想插值(例如)颜色字符串或变换矩阵,请提供一个自定义插值器
你也可以调用 progress.set(value, options) 而不是直接赋值给 progress.target,这种情况下 options 将覆盖默认值。set 方法返回一个 Promise,该 Promise 在补间完成时 resolve。
上一页 下一页
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<script>
let progress = $state(0);
</script>
<progress value={progress}></progress><button onclick={() => (progress = 0)}>0%
</button>
<button onclick={() => (progress = 0.25)}>25%
</button>
<button onclick={() => (progress = 0.5)}>50%
</button>
<button onclick={() => (progress = 0.75)}>75%
</button>
<button onclick={() => (progress = 1)}>100%
</button>
<style>
progress {display: block;
width: 100%;
}
</style>