javascript - 跨动态加载元素的连续动画
问题描述
我需要在通过 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' 有不同的动画,它们在这些元素的动态替换中都是连续的。
谢谢
解决方案
这似乎是一个单独使用 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 不是您可以使用的东西,那么请寻找具有更好支持的框架,例如GreenSock或AnimeJS。这篇文章还列出了一些不错的选择。
希望这会有所帮助,祝您有美好的一天!
推荐阅读
- jq - 如何检查 jq 中的可选字段?
- angular - ngFor多维json对象
- arduino - 将十六进制字符串颜色转换为 uint_16
- javascript - 缩小画布元素然后获取 imageData
- python - requests-html "RuntimeError: 在烧瓶端点上使用线程 'Thread-1' 时没有当前事件循环
- javascript - javascript如何在主题标签上进行正则表达式匹配和替换但排除主题标签字符
- vue.js - 使用 laravel-mix webpack 中的“extract”方法提取 Vue 时是否有 bug
- angular - 有没有办法通过将服务注入/导入到不是组件/服务/存储库的类中来提高代码质量?
- python - 为什么我得到“支持的目标类型是:('binary', 'multiclass')。改为'continuous'。” 错误?
- javascript - 组件渲染两次