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

问题描述 投票:0回答:1

根据Mozilla Web Animations API文档,"Document接口的getAnimations()方法会返回一个当前有效的所有Animation对象的数组,其目标元素是文档的后裔。这个数组包括CSS Animations、CSS Transitions和Web Animations。"

有没有办法用这个方法只把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, … ]
javascript web-animations web-animations-api
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>
© www.soinside.com 2019 - 2024. All rights reserved.