[英]animationEnd Eventlistener fires multiple times
Html: Html:
<div id="click">Click</div>
<div id="animateElement">I get animated</div>
CSS: CSS:
#animateElement {
height: 100px;
height: 100px;
background: green;
}
.animate {
animation: blue 2s linear forwards;
}
@keyframes blue {
from {
background: red;
}
to {
background: blue;
}
}
Javascript: Javascript:
document.getElementById('click').addEventListener('click', function (e) {
document.getElementById('animateElement').classList.toggle('animate');
document.getElementById('animateElement').addEventListener('animationend',function(e){
alert('animated');
});
}, false);
First Click is ok, next Clicks fires twice, third click 4 times etc.... Is there a way to prevent this?第一次点击没问题,下一次点击触发两次,第三次点击 4 次等等......有没有办法防止这种情况? I tried to remove the eventlistener but i had no success...
我试图删除事件监听器,但我没有成功......
Each time the click
event listener is called, an additional animationend
event listener is added to #animateElement
.每次调用
click
事件侦听器时,都会向#animateElement
添加一个额外的animationend
事件侦听器。 You can resolve this by de-nesting the registering of event listeners:您可以通过取消嵌套事件侦听器的注册来解决此问题:
document.getElementById('click').addEventListener('click', function (e) {
document.getElementById('animateElement').classList.toggle('animate');
}, false);
document.getElementById('animateElement').addEventListener('animationend',function(e) {
alert('animated');
});
You might be interested in reading up on how event listeners work on the MDN Web Docs .您可能有兴趣阅读MDN Web 文档上的事件侦听器如何工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.