JS EventListener animationend启动太早

时间:2018-09-08 20:44:52

标签: javascript

我需要使用带有平滑过渡的js更改元素的宽度和高度。我的想法是向元素添加一个类,以使过渡平滑,更改宽度和高度,并在完成过渡后再次删除该类。我使用以下代码:

    element.classList.add("smoothTransition")
    element.classList.toggle("fullscreen")
    element.addEventListener("webkitAnimationEnd", element.classList.remove("smoothTransition"));
    element.addEventListener("animationend", element.classList.remove("smoothTransition"));

可悲的是,没有过渡发生。没有eventListener,过渡就会发生。转换开始后,eventListener也会触发。

1 个答案:

答案 0 :(得分:2)

您的问题出在您的addEventListener中:

element.addEventListener("webkitAnimationEnd", element.classList.remove("smoothTransition"));
element.addEventListener("animationend", element.classList.remove("smoothTransition"));

addEventListener的第二个参数必须是一个函数,而不是函数调用的结果(在您的情况下为未定义)。因此,将前几行更改为:

element.addEventListener("webkitAnimationEnd", function(e) {
    this.classList.remove("smoothTransition")
});
element.addEventListener("animationend", function(e) {
    this.classList.remove("smoothTransition")
});

您可以考虑在转换之前添加事件监听器。

document.addEventListener("DOMContentLoaded", function(e) {
  var element = document.querySelector('.box');
  element.addEventListener("webkitAnimationEnd", function(e) {
      this.classList.remove("smoothTransition");
      console.log('webkitAnimationEnd');
  });
  element.addEventListener("animationend", function(e) {
      this.classList.remove("smoothTransition");
      console.log('animationend');
  });
  element.classList.add("smoothTransition")
  element.classList.toggle("fullscreen")
});
.box {
    width: 150px;
    height: 150px;
    background: red;
    margin-top: 20px;
    margin-left: auto;
    margin-right: auto;
}
@keyframes colorchange {
    0% { background: yellow }
    100% { background: blue }
}
.smoothTransition {
    animation: colorchange 2s;
}
.fullscreen {
    width: 100%;
    height: 100vh;
}
<div class="box"></div>

相关问题