animate.css js 操作

441 阅读1分钟

第一、检测动画结束

const element = document.querySelector('.my-element');
element.classList.add('animate__animated', 'animate__bounceOutLeft');

element.addEventListener('animationend', () => {
  // do something
});

aniation 事件

  • animationstart- CSS 动画开始后触发
  • animationiteration - CSS 动画重复播放时触发
  • animationend - CSS 动画完成后触发

Chrome, Safari 和 Opera 浏览器使用 webkitAnimationEnd 前缀

object.addEventListener("webkitAnimationEnd", *myScript*);  // Chrome, Safari 和 Opera*
object*.addEventListener("animationend", *myScript*);        // 标准语法

第二、更改动画持续时间

const element = document.querySelector('.my-element');
element.style.setProperty('--animate-duration', '0.5s');

第三、自动添加动画并删除

const animateCSS = (element, animation, prefix = 'animate__') =>
  // We create a Promise and return it
  new Promise((resolve, reject) => {
    const animationName = `${prefix}${animation}`;
    const node = document.querySelector(element);

    node.classList.add(`${prefix}animated`, animationName);

    // When the animation ends, we clean the classes and resolve the Promise
    function handleAnimationEnd(event) {
      event.stopPropagation();
      node.classList.remove(`${prefix}animated`, animationName);
      resolve('Animation ended');
    }

    node.addEventListener('animationend', handleAnimationEnd, {once: true});
  });