Javascript 检测到 animationend 就好像它是 animationstart

标签 javascript html css css-animations

我试图在动画结束后触发一个函数,但它甚至在动画开始之前就触发了。我不知道出了什么问题。我多次检查了我的代码,甚至做了一个更简单的代码,这就是我在这里展示的代码。

我有一个通过 CSS 动画的元素,另一个通过 CSS 隐藏:

<div class= "container">
  <div id="animated" style="background-color: lime; animation: changeColour 5s;">CONTENT</div>
  <div id="hidden" style="visibility: hidden;">CONTENT</div>
</div>

然后,我让 Javascript 设置事件监听器以将“隐藏”可见性属性更改为“可见”

var elementHidden = document.getElementById("hidden")
var elementAnimated = document.getElementById("animated")
elementAnimated.addEventListener("animationend", afterAnimation());

function afterAnimation() {
  elementHidden.style.visibility = "visible";
}

这是我的动画:

@keyframes changeColour {
  0% {background-color: lime}
  50% {background-color: aqua}
  100% {background-color: lime}
}

最佳答案

立即导致afterAnimation 运行,因为您正在调用它使用:afterAnimation()

事件监听器希望引用函数。

换句话说:

// Not this
elementAnimated.addEventListener("animationend", afterAnimation());

// This
elementAnimated.addEventListener("animationend", afterAnimation /* without () */);

按照您现在编写的方式,afterAnimation 会立即更改可见性,然后隐式返回 undefined。你基本上是在写:

afterAnimation();
elementAnimated.addEventListener("animationend", undefined);

关于Javascript 检测到 animationend 就好像它是 animationstart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48649305/

相关文章:

javascript - 如何检查对象是否为日期?

javascript - 尽管输入被禁用,jQuery 函数仍运行多次?

javascript - 在同一行中多次匹配字符串模式

html - <li> 中的副标题与 CSS 内联不对齐

java - 如何使用 Java 向 Google Chrome 图像发送请求?

html - DOM 元素变量以获得第 N 个结果?

html - 并排设置两组div类

javascript - 将日期字符串转换为日期

html - 具有相对和绝对定位的元素

css - 分隔表中的 <th> 个元素