如何使用 CSS 动画以不同的速度滑动 children。当 children 的 # 未知时,可以动态完成吗?

How to slide children at different speeds with CSS animation. Can this be done dynamically when # of children unknown?

我想从右到左滑动容器元素的每个 children,child 元素按自上而下的顺序完成动画。(项目 1 完成动画然后项目2、item3等)不知道children的人数怎么办?

<div class="container">
        <div class="child"> item 1</div>
        <div class="child"> item 2</div>
        <div class="child"> item 3</div>
        <div class="child"> item 4</div>
    </div>

我看到很多关于在单个元素上从右向左滑动的指南​​。但是,没有看到以各种速度滑动单个项目的方法,尤其是在项目数量未知的情况下。

如果您知道项目的最大数量,则可以为每个可能的元素设置动画时间。

然后您需要为每个元素动态添加一个 class。由于项目是动态显示的,我假设您使用的是地图之类的东西。

items.map((items, itemCount=0)=> {
   //code to append class with itemCount++ at end
}

然后在你的CSS中你可以做这样的事情

.item1 {
  animation: 100ms slide-left;
}

.item2 {
  animation: 200ms slide-left;
}
.item3 {
  animation: 300ms slide-left;
}

@keyframes slide-left {
  from {
    margin-left: 100%;
  }
  to {
    margin-left: 0%;
  }
}

注意我们如何使用相同的动画,只需更改每个子元素的时间,使其滑动得更快或更慢。

首先你必须给每个“child”一个自己的class,你将它们列为相同的class。 前任。 child1,child2,等等。 我在下面列出了我认为是您要问的代码。 注释掉的代码将解释该怎么做:)

代码:

<!doctype html>
<html>
<head>

    <title>JavaScript and the Canvas</title>
    
    <style>
 /* animate every child*/
 /*add an animation delay for each one so they will start one after the other 
 ex. if one starts at 3s then the next will be delayed by 3s so it starts after it*/
 /*if you want the animation to continue almost on a loop add: animation-iteration-count: infinite;*/

.container {
    background-color: aquamarine;
    height: 500px;
    width: 500px;
}
.child1 {
    color: blue;
    animation-name: move1;
   animation-duration: 3s;
   animation-timing-function: ease-in-out;

}
@keyframes move1 {
 
 0% {
     transform: translate(0);
 }
 50% {
     transform: translate(100px);
 }
 100% {
     transform: translate(450px);
 }
 }

.child2 {
    color: blueviolet;
    animation-name: move2;
   animation-duration: 3s;
   animation-delay: 3s;
   animation-timing-function: ease-in-out;
}
@keyframes move2 {
 
 0% {
     transform: translate(0);
 }
 50% {
     transform: translate(100px);
 }
 100% {
     transform: translate(450px);
 }
 }
.child3 {
    color: brown;
    animation-name: move3;
   animation-duration: 3s;
   animation-delay: 6s;
   animation-timing-function: ease-in-out;
}
@keyframes move3 {
 
 0% {
     transform: translate(0);
 }
 50% {
     transform: translate(100px);
 }
 100% {
     transform: translate(450px);
 }
 }

    </style>
    
</head>
<body>
 <!--give each child in the container a diffrent class, not the same class-->
    <div class="container">
        <div class="child1"> item 1</div>
        <div class="child2"> item 2</div>
        <div class="child3"> item 3</div>
    </div>

</body>
</html>