【问题标题】:Javascript events not working with Element.animate()Javascript 事件不适用于 Element.animate()
【发布时间】:2021-08-16 11:17:35
【问题描述】:

我正在尝试使用 Javascript 中的 Element.animate() 方法将动画添加到我的网站,但我意识到在运行动画时不会触发动画事件。

这是我的代码:

window.onload = function () {
  let list = document.querySelector(".list");
  let btn = document.querySelector(".btn");

  // animation events
  list.addEventListener('animationstart', () => {
    console.log('start')
  });

  list.addEventListener('animationend', () => {
    console.log('end');
  });


  btn.onclick = () => {
    list.animate([
      // keyframes
      { transform: 'translateY(0px)' },
      { transform: 'translateY(-24px)' }
    ], {
      // timing options
      duration: 1000,
      fill: "forwards"
    });
  }

}

在上面的代码中,动画运行但动画事件没有被触发。谁能解释为什么这不起作用或告诉我如何解决它?

【问题讨论】:

    标签: javascript html css animation


    【解决方案1】:

    您没有使用 CSS 动画(由 css 类触发)。只有在使用 CSS 定义的动画或 -transition 时才会触发动画开始/结束(或过渡开始/结束)事件。

    看看HTMLElement: animationstart event的例子。

    您可以直接访问Animation-instance,而不是开始/结束事件:

    btn.onclick = () => {
      // animation started
      let animation = list.animate(...);
      animation.onfinish = () => {
        // animation ended
      };
    };
    

    【讨论】:

    • 感谢您的回复。这很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 2012-04-18
    相关资源
    最近更新 更多