简体   繁体   English

JS EventListener animationend 触发过早

[英]JS EventListener animationend firing too early

I need to change the width and height of an element using js with a smooth transition.我需要使用具有平滑过渡的 js 更改元素的宽度和高度。 My idea was to add a class to the element which makes the transition smooth, change the width and height, and once the transition is done, removing the class again.我的想法是向元素添加一个类,使过渡平滑,更改宽度和高度,一旦过渡完成,再次删除该类。 I use the following code:我使用以下代码:

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

Sadly no transition is happening.遗憾的是,没有发生任何转变。 Without the eventListener the transition is happening.没有 eventListener 转换正在发生。 Also the eventListener does trigger, right after the transition starts. eventListener 也会在转换开始后立即触发。

Your issue is in your addEventListener:您的问题在您的 addEventListener 中:

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

The second argument of addEventListener must be aa function and not the result of a function call (in your case undefined ). addEventListener的第二个参数必须是一个函数,而不是函数调用的结果(在您的情况下为undefined )。 Hence, change the previous lines to:因此,将前面的行更改为:

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

You may consider to add your event listeners before transitions.您可以考虑在转换之前添加事件侦听器。

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM