You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue2:使用Anime.js实现插槽内.modal-slot子元素交错入场动画的问题

实现.modal-slot子元素的交错入场动画

嘿,我明白你想给.modal-slot里的每个子元素做交错入场动画,但直接给父容器加动画只能让整个块一起动,没法单独控制每个子节点——这确实是个常见的小坑!下面给你两种实用的解决方案,不管你子元素数量固定还是动态生成都能用:

方案1:纯CSS实现(适合子元素数量固定的场景)

这种方法不需要额外的JS,利用CSS的:nth-child()选择器给每个子元素分配递增的动画延迟,就能实现自然的交错效果:

/* 先给父容器设置基础布局,比如flex/grid */
.modal-slot {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

/* 给所有直接子元素设置初始状态和动画 */
.modal-slot > * {
  opacity: 0;
  transform: translateY(20px); /* 初始向下偏移,入场时回到原位 */
  animation: fadeInUp 0.5s forwards; /* forwards让动画停在最后一帧 */
}

/* 给每个子元素设置递增的动画延迟 */
.modal-slot > *:nth-child(1) { animation-delay: 0.1s; }
.modal-slot > *:nth-child(2) { animation-delay: 0.2s; }
.modal-slot > *:nth-child(3) { animation-delay: 0.3s; }
.modal-slot > *:nth-child(4) { animation-delay: 0.4s; }
/* 如果有更多子元素,继续往下加就行 */

/* 定义入场动画 */
@keyframes fadeInUp {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

为什么这个方法有效?

直接给父元素加动画只会让整个容器作为一个整体动起来,而我们这里是给每个直接子元素单独绑定动画,再通过animation-delay让它们依次触发,自然就形成了交错入场的效果。

方案2:JavaScript动态控制(适合子元素数量不固定的场景)

如果.modal-slot里的子元素是动态生成的(比如从接口拉取、或者通过框架的循环渲染生成),纯CSS的写法就不够灵活了,这时候用JS动态计算延迟更靠谱:

/* 先在CSS里定义好动画 */
@keyframes fadeInUp {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-slot {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}
// 获取父容器和所有子元素
const modalSlot = document.querySelector('.modal-slot');
const childElements = Array.from(modalSlot.children);

// 遍历每个子元素,设置动画和延迟
childElements.forEach((child, index) => {
  // 设置初始状态
  child.style.opacity = '0';
  child.style.transform = 'translateY(20px)';
  // 绑定动画,延迟时间根据索引递增(比如每0.1s触发一个)
  child.style.animation = 'fadeInUp 0.5s forwards';
  child.style.animationDelay = `${index * 0.1}s`;
});

注意事项

如果是用Vue、React这类框架开发,记得要在元素挂载完成后再执行这段JS代码(比如Vue的mounted钩子、React的useEffect),确保能获取到已经渲染好的子元素。

额外小技巧

你也可以结合CSS变量来简化纯CSS的写法,让延迟计算更直观:

.modal-slot > * {
  --delay: calc(var(--child-index) * 0.1s);
  opacity: 0;
  transform: translateY(20px);
  animation: fadeInUp 0.5s var(--delay) forwards;
}

.modal-slot > *:nth-child(1) { --child-index: 1; }
.modal-slot > *:nth-child(2) { --child-index: 2; }
/* 以此类推 */

内容的提问来源于stack exchange,提问作者Donnie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 06:56:55