0

根据 Mozilla Web Animations API 文档,“Document 接口的 getAnimations() 方法返回一个当前有效的所有动画对象的数组,其目标元素是文档的后代。这个数组包括 CSS 动画、CSS 过渡和 Web 动画。”

有没有办法使用它只将 Web 动画对象添加到数组中,不包括 CSS 动画和 CSS 过渡?

以下代码返回文档上的所有动画:

        var allAnimations;
        if (typeof document.getAnimations === 'function') {
            allAnimations = document.getAnimations();
        } else {
            allAnimations = document.timeline.getAnimations();
        }

allAnimations 数组结果是这样的:

Array(72) [ CSSTransition, CSSTransition, CSSTransition, CSSTransition, CSSTransition, CSSTransition, Animation, Animation, Animation, Animation, … ]

我希望它只包含网络动画,所以像这样:

Array(66) [ Animation, Animation, Animation, Animation, Animation, Animation, Animation, Animation, Animation, Animation, … ]
4

1 回答 1

1

您可以使用 来检查您正在查看的动画类型instanceof,并使用它来过滤列表:

const animations = [
  ...document.getAnimations(),
  new Animation(),
];

const isCSSAnimation = x => x instanceof CSSAnimation;

const onlyAnimations = animations.filter(x => x.constructor.name === 'Animation');

console.dir(animations);

console.dir(onlyAnimations);
.animated {
  -webkit-animation-duration: .5s;
  animation-duration: .5s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
  -webkit-animation-timing-function: linear;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
  -webkit-animation-iteration-count: infinite;
}
@-webkit-keyframes bounce {
  0%, 100% {
    -webkit-transform: translateY(0);
  }
  50% {
    -webkit-transform: translateY(-5px);
  }
}
@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-5px);
  }
}
.bounce {
  -webkit-animation-name: bounce;
  animation-name: bounce;
}
#animated-example {
  width: 20px;
  height: 20px;
  background-color: red;
  position: relative;
  top: 100px;
  left: 100px;
  border-radius: 50%;
}
hr {
  position: relative;
  top: 92px;
  left: -300px;
  width: 200px;
}
<div id="animated-example" class="animated bounce"></div>

于 2020-06-07T14:33:04.000 回答