【发布时间】:2019-06-21 05:55:03
【问题描述】:
我正在尝试在元素的淡入淡出动画结束后删除它。向animationend 事件添加监听器可以正常工作,但将处理程序分配给.onanimationend 则不行——动画结束时函数不会触发。为什么on- 处理程序不起作用?
我在 FF 48 上运行代码,但问题也出现在 Chrome 71 上。
const post = document.querySelector('.post');
const hideButton = post.children[0];
// When hide button is clicked, run fade animation.
hideButton.onclick = function() {
post.style.animationPlayState = "running";
};
// This function runs
post.addEventListener("animationend", function() {
console.log('animationend listener running');
// this.remove();
});
// This function doesn't run
post.onanimationend = function() {
console.log('onanimationend handler running');
// this.remove();
};
@keyframes hide {
0% {
opacity: 1;
height: 100%;
margin: 10px 0;
padding: 15px;
}
75% {
opacity: 0;
height: 100%;
margin: 10px 0;
padding: 15px;
}
100% {
opacity: 0;
height: 0px;
margin: 0px;
padding: 0px;
}
}
.post {
background-color: #80ff00;
margin: 10px 0;
padding: 15px;
animation-name: hide;
animation-duration: 2s;
animation-fill-mode: forwards;
animation-play-state: paused;
}
<div class="post">
Post
<button class="hide">
Hide
</button>
</div>
【问题讨论】:
-
我可以在 Chrome 71 上重现该问题。该元素看起来在 FF 56 上已被正确删除。听起来像是浏览器问题,而不是您的代码问题。
-
是的,其实是浏览器的问题。我编辑了我的答案。
标签: javascript css css-animations