我试图在元素的淡入淡出动画结束后删除它。将监听器添加到 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>
最佳答案
检查您的浏览器版本并与 https://caniuse.com/#search=animationend
Firefox v48.0.0 – Java Broker 36 mins ago
您的浏览器与animationend
不兼容
关于javascript - 为什么 onanimationend 在我的代码中不起作用,但 addEventListener ("animationend") 可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54398450/