首页 > 解决方案 > 为什么在屏幕加载 0.5 秒时动画没有消失?

问题描述

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

codepen.io/codemakker/pen/abJpwjr

感谢您的帮助!

标签: javascriptloader

解决方案


我不确定您是否希望组消失,但如果您只是希望组在动画完成后消失并在 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()

推荐阅读