我有一个显示该百分比的进度条,我遇到的问题是它没有正确更新,我试图在半秒后从0开始加载它,然后显示$progress
值会增加,但是目前它最初跃升至50%左右,但随后一直保持在该水平,并且不再更新。
如何获取以显示更新进度?
<script>
import { progress } from '../../store';
let width = 0
setTimeout(() => width = $progress, 500)
$: animatedWidth = width
</script>
<div class="container">
<div class="line">
<div class="animation" style="width: {animatedWidth}%"></div>
</div>
</div>
答案 0 :(得分:0)
您可以结合使用setTimeout
和setInterval
。我使用以下代码为您创建了REPL:
<script>
import { onMount } from "svelte";
let width = 0;
let interval;
onMount(() => {
setTimeout(() => {
width = 1;
interval = setInterval(() => {
if (width <= 100) {
width += 1;
} else {
clearInterval(interval);
}
}, 1000);
}, 500);
});
$: animatedWidth = width;
</script>
您基本上要做的是在延迟500毫秒后使用setTimeout启动动画。之后,它将更新宽度,直到达到100,然后结束间隔。为了简化示例,我使用1作为起始值,但是您可以使用导入的商店值轻松地完成此操作。
答案 1 :(得分:0)
如果您希望补间的商店不使用CSS进行动画处理,也可以使用补间的商店,这非常简单,这是一个REPL:https://svelte.dev/repl/6ef1130a13f641f2bf72c67a16ea429f?version=3.22.3
<script>
import { readable } from 'svelte/store';
import { tweened } from 'svelte/motion';
import { cubicOut } from 'svelte/easing';
const time = readable(new Date(), function start(set) {
const interval = setInterval(() => {
set(new Date());
}, 1000);
return function stop() {
clearInterval(interval);
};
});
const width = tweened(0, {
duration: 300,
easing: cubicOut,
delay: 3000
});
let started = false;
$: if(started) {
width.set($time.getSeconds());
}
</script>
<p>
{$width}
</p>
{#if !started}
<button on:click={() => started = true}>
Start
</button>
{/if}
我创建了time
商店来代替您的商店(因为您没有提供代码)。 width
存储是重要的部分,它将第一次更新延迟3秒,然后一直保持更新。显然,一旦达到极限,它将变为0,因为一分钟只有60秒。 ;)您只需要订阅time
商店:width.set($time.getSeconds());
因此,基本上您要做的就是导入补间商店并使用:
const width = tweened(0, {
duration: 300,
delay: 500
});
width.set($progress);
然后将元素宽度设置为{$width}
。