【问题标题】:Continuous animation across dynamically loaded elements跨动态加载元素的连续动画
【发布时间】:2022-03-18 16:44:25
【问题描述】:

我需要有一个连续运行的 CSS @keyframe 动画元素,这些元素通过 ajax/fetch 动态添加、销毁和替换。

但是将动画绑定到动态添加的元素会使动画在每次替换元素时从 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”有不同的动画,它们在这些元素的动态替换中都是连续的。

谢谢

【问题讨论】:

    标签: javascript ajax css-animations


    【解决方案1】:

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

    您可以查看Web Animations API。目前browser support 不是很好,但未来可能会变得更好。

    但是,它确实具有您正在寻找的功能。正如this article on 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 不是您可以使用的东西,那么请寻找具有更好支持的框架,例如 GreenSockAnimeJSThis article 也有一个不错的选择列表。

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

    【讨论】:

      猜你喜欢
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      • 2016-08-06
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多