首页 > 解决方案 > 跨动态加载元素的连续动画

问题描述

我需要在通过 ajax/fetch 动态添加、销毁和替换的元素之间连续运行 CSS @keyframe 动画。

但是将动画绑定到动态添加的元素会使动画在每次替换元素时从 0% 重新开始。

部分解决方案是将动画绑定到不可变的父元素。然后动画将连续运行并影响任何子元素,即使它们被动态替换。

但是这个解决方案是有限的,因为我无法选择哪个动画由哪个子元素继承。

对于此代码:

HTML

<div class='parent'>
  <div class='child one'>Some text</div>
  <div class='child two'>Other text</div>
</div>

CSS (SASS)

.parent
  animation: BY 15s infinite alternate

.child.two
  animation: RG 15s infinite alternate

@keyframes BY
  0%
    color: blue
  100%
    color: yellow

@keyframes RG
  0%
    color: red
  100%
    color: green

只有“.parent”中影响“.child.one”文本的 BY 动画在“.child.one”的任何动态替换中保持连续。而“.child.two”的动画每次动态替换时都会以 0% 重新启动。

这是一个说明这种行为的代码笔:https ://codepen.io/plagasul/pen/WNerBvO

我希望 '.child.one' 和 '.child.two' 有不同的动画,它们在这些元素的动态替换中都是连续的。

谢谢

标签: javascriptajaxfetchcss-animations

解决方案


这似乎是一个单独使用 CSS 可能无法解决的问题。如果我理解正确,您希望被另一个孩子替换的孩子的动画从上一个动画结束的地方开始。

您可以查看Web Animations API。目前浏览器支持不是很好,但将来可能会变得更好。

但是,它确实具有您正在寻找的功能。正如MDN 上的这篇文章中所引用的,可以通过使用动画的currentTime属性来获取动画应该从哪里开始的时间点。

// Just like with CSS we use keyframes to create an animation.
const keyframes = [
    { 
        color: 'blue' 
    },
    { 
        color: 'yellow' 
    }
];

// Set the timing properties of the animation just like you have in CSS.
const timing = {
    duration: 15000,
    direction: 'alternate',
    iterations: Infinity,
};

// And add it all together.
const currentAnimation = document.querySelector('.child').animate(keyframes, timing);

这里的代码是 CSS 动画的 JavaScript 等价物。.child只要元素存在,类的颜色就会改变,就像在 CSS 中一样。

在用新的孩子替换孩子之前,您需要知道动画在时间方面的位置。currentTime通过访问前面提到的属性来获取它。

// Returns the position in time of the animation in milliseconds.
const position = currentAnimation.currentTime;

所以现在你有了动画的位置。您可以使用它在新元素上设置动画的起点。像这样:

// Create a new animation
const newAnimation = docum... // You know the drill.

// Update the currentTime with the position of the previous animation.
newAnimation.currentTime = position;

新动画将从我们存储的位置开始。

您仍然需要将这些示例包装到函数中以在代码中使用它们,但我希望您能弄清楚这一点。如果 Web Animations API 不是您可以使用的东西,那么请寻找具有更好支持的框架,例如GreenSockAnimeJS这篇文章还列出了一些不错的选择。

希望这会有所帮助,祝您有美好的一天!


推荐阅读