如何使用 WAAPI Document.getAnimations() 函数只获取 WAAPI 动画对象

How to use WAAPI Document.getAnimations() function to get only WAAPI animation objects

根据 Mozilla 网络动画 API 文档,"The getAnimations() method of the Document interface returns an array of all Animation objects currently in effect whose target elements are descendants of the document. This array includes CSS Animations, CSS Transitions, and Web Animations."

有什么方法可以使用它只将 Web 动画对象添加到数组中,不包括 CSS 动画和 CSS 过渡?

以下代码returns文件上的所有动画:

        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, … ]

您可以使用 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>