javascript - 为什么在屏幕加载 0.5 秒时动画没有消失?
问题描述
我希望动画在加载后立即消失 0.5 秒。
codepen.io/codemakker/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 而不是使用上面的嵌套回调。为此,您可以创建一个自定义延迟函数,该函数在指定时间后返回一个承诺。然后您可以在异步函数中使用该延迟函数,该函数将等待每个延迟函数完成执行,然后再移动到其他任务。
这是代码:
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()
推荐阅读
- android - 在服务或活动之外使用 AltBeacon BeaconManager
- javascript - 找不到模块:无法解析:Material-UI
- angular - 如何从 2 个 Angular 的 http 请求构建单个对象,而不添加另一个值
- python-3.x - 使用 SymPy 求解具有不同阶数的 ODE 系统
- r - 如何提取具有特定颜色的所有单元格值(以及它们的单元格 ID)?
- vue.js - 使用 v-select 下拉菜单作为默认值
- sql - 如何从 SQL Server CE 中的另一个表中选择最大值和最小值
- python - 如何绘制具有固定边界的波动方程
- c# - 如何在 html 数据表视图中显示 IEnumerable 数据分组 ID?
- compiler-errors - 在树莓派零上工作。显示错误。在编译 opencv 时,我使用 make ~j4 而不是 make。是这个原因吗?