【发布时间】:2021-05-20 20:06:05
【问题描述】:
我希望动画在加载后立即消失 0.5 秒。
codepen.io/codemakker/pen/abJpwjr
感谢您的帮助!
【问题讨论】:
-
codepen.io 的链接必须附有代码。请不要忘记使用代码工具栏按钮或 CTRL+K 键盘快捷键将所有代码缩进 4 个空格。
标签: javascript loader
我希望动画在加载后立即消失 0.5 秒。
codepen.io/codemakker/pen/abJpwjr
感谢您的帮助!
【问题讨论】:
标签: javascript loader
我不确定你是否想让群组消失,但如果你只是想让群组在动画完成后消失并在 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 而不是使用上面的嵌套回调。为此,您可以创建一个自定义延迟函数,该函数在指定时间后返回一个承诺。然后您可以在异步函数中使用该延迟函数,该函数将等待每个延迟函数完成执行,然后再转移到其他任务。
代码如下:
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()
【讨论】: