- 定义动画函数:
- 在Svelte中,可以通过
animate
函数来定义动画。首先需要导入animate
函数,通常在组件的<script>
标签内进行。
- 例如,定义一个淡入动画函数:
<script>
import { animate } from'svelte/animate';
const fadeIn = (node, { delay = 0, duration = 400 }) => {
const o = +getComputedStyle(node).opacity;
return {
delay,
duration,
css: (t) => `opacity: ${t * o}`
};
};
</script>
- 这里,
node
是要应用动画的DOM节点,{ delay = 0, duration = 400 }
是动画的配置参数,delay
表示动画延迟时间,duration
表示动画持续时间。getComputedStyle(node).opacity
获取节点初始的透明度,然后在动画过程中通过t
(0到1之间的动画进度值)来改变透明度。
- 在组件中应用动画:
- 假设在组件中有一个元素要应用这个淡入动画,比如一个
<div>
元素。
<script>
import { animate } from'svelte/animate';
const fadeIn = (node, { delay = 0, duration = 400 }) => {
const o = +getComputedStyle(node).opacity;
return {
delay,
duration,
css: (t) => `opacity: ${t * o}`
};
};
</script>
<div use:fadeIn>
这是一个淡入的元素
</div>
- 使用
use:动画函数名
的语法将定义好的动画函数fadeIn
应用到<div>
元素上。这样,当这个<div>
元素出现在页面上时,就会执行淡入动画。