我正在尝试向元素添加animationend
事件,但事件不会被触发。我做错了什么,我该如何解决?
var btn = document.getElementById('btn');
var elem = document.getElementById('elem');
var timeOutFunc;
btn.addEventListener('click', function() {
elem.classList.add('show');
clearTimeout(timeOutFunc);
timeOutFunc = setTimeout(function() {
elem.classList.remove('show')
}, 1000);
});
elem.addEventListener('animationend', function(e) {
console.log('animation ended');
});
#elem {
background-color: orange;
width: 100px;
height: 100px;
opacity: 0;
transition: opacity 500ms ease;
}
#elem.show {
opacity: 1;
transition: none;
}
<button id="btn">Press Me</button>
<div id="elem"></div>
答案 0 :(得分:14)
有两个独立的动画事件。
使用css transition
时使用transitionend
,使用@keyframes/animation
时,请使用animationend
。
答案 1 :(得分:0)
您需要修改元素的动画样式属性,这是您在Jsfiddle
的更新示例 #elem {
background-color: orange;
width: 100px;
height: 100px;
opacity: 0;
transition: opacity 500ms ease;
}
/* Chrome, Safari, Opera */
@-webkit-keyframes myopacity {
0% { opacity: 0; }
100% { opacity: 1; }
}
@keyframes myopacity {
0% { opacity: 0; }
100% { opacity: 1; }
}
#elem.show {
WebkitAnimation : myopacity 1s 1;
animation : myopacity 1s 1;
}
var btn = document.getElementById('btn');
var elem = document.getElementById('elem');
var timeOutFunc;
btn.addEventListener('click', function() {
elem.classList.add('show');
/* clearTimeout(timeOutFunc);
timeOutFunc = setTimeout(function() {
elem.classList.remove('show')
}, 1000);*/
});
elem.addEventListener('animationend', function(e) {
console.log('');
alert('animation ended');
elem.classList.remove('show')
});
<button id="btn">Press Me</button>
<div id="elem"></div>