为什么动画在屏幕上加载 0.5 秒时不会消失?



我希望动画加载后立即消失0.5秒。

codepen.io/demaker/pen/abJpwjr

谢谢你的帮助!

我不确定你是否希望组淡出,但如果你只希望组在动画完成后消失,0.5秒后重新出现,你可以添加以下代码:

const svg = document.querySelector('svg') // selecting entire svg group
setTimeout(() => {
svg.style.opacity = 0
setTimeout(() => {
svg.style.opacity = 1
}, 500)
}, 3000)

在本例中,我在setTimeout中使用了setTimeout。动画需要3秒,所以我要确保在动画结束之前不要将svg的不透明度设置为0。一旦svg的不透明度为0,我们就可以使用另一个setTimeout在0.5秒后将其不透明度设置回1。


奖金:

解决这个问题的一个更优雅的方法是使用Promises,而不是使用上面的嵌套回调。为此,您可以创建一个自定义延迟函数,在指定的时间后返回promise。然后,您可以在异步函数中使用该延迟函数,该函数将等待每个延迟函数完成执行,然后再转到其他任务。

这是代码:

const svg = document.querySelector('svg')
// delay function returns Promise after "ms" amount of time
const delay = (ms) => new Promise(
(resolve, reject) => setTimeout(resolve, ms)
)
// this is the asynchronous function that would execute the animation
const blinkSvg = async () => {
await delay(3000) // wait for 3s/3000ms before moving to next line
svg.style.opacity = 0
await delay(500)
svg.style.opacity = 1
}
blinkSvg()

最新更新