animationend event not firing

£可爱£侵袭症+ 提交于 2020-03-21 17:42:06

问题


I am trying to add an animationend event to an element, but the event doesn't get fired. What am I doing wrong, and how can I fix it?

JSFiddle

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>

回答1:


There are two separate animating events.

  1. animationend
  2. transitionend

When using the css transition use transitionend, and when using @keyframes/animation, use animationend.




回答2:


You need to modify the animation style property of the element this is your updated example at 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>


来源:https://stackoverflow.com/questions/41530263/animationend-event-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!