Javascript检测animationend就好像它是animationstart一样

时间:2018-02-06 18:06:54

标签: javascript html css css3 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}
}

1 个答案:

答案 0 :(得分:4)

imediately 导致afterAnimation运行,因为您使用afterAnimation()调用它。

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

换句话说:

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

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

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

afterAnimation();
elementAnimated.addEventListener("animationend", undefined);
相关问题