CSS动画 animation-play-state属性

250 阅读1分钟

参考

  1. animation-play-state
  2. onanimationend

问题

今天发现了项目中使用了一个第三方的信息提示插件coco-message,但是这个插件在手机上使用时造成了一个bug,当手指点击到message弹出框后,倒计时关闭的功能暂停了,导致错误的提示框挡住了登录界面。

image.png

在我没看coco-message源代码之前,我以为是给弹出框加了一个touchstart事件监听,来控制动画倒计时。然而当我准备修改源码时,并没有找到。经过一番探索,我找到如下代码:

var anm = el.querySelector(".coco-msg__circle");

if ("onanimationend" in window) {
    addAnimationEnd(anm, function () {
      closeMsg(el, onClose);
    });
} 

function addAnimationEnd(el, fn) {
    ["a", "webkitA"].forEach(function (prefix) {
      var name = prefix + "nimationEnd";
      el.addEventListener(name, function () {
        fn();
      });
    });
}

这段代码的意思是给coco-msg__circle元素添加animationEnd事件,当coco-msg_circle的动画结束时,执行回调函数。

但是,这也不是控制动画暂停和播放的。

继续探索.coco-msg_circle这个元素相关的代码,发现他的CSS动画包含这些属性:

.coco-state: hover .coco-msg__circle {
    -webkit-animation-play-state:paused!important;
    animation-play-state:paused!important
}

查看文档的得知animation-play-state属性规定动画正在运行还是暂停。当然就可以在javascript中使用该属性,能够控制动画的播放和暂停。

object.style.animationPlayState = "running" | "paused"

动手实践

实现一个在正方形中左右移动的球,用hover或者js控制

在线demo