两个球弹跳动画组合时不起作用

问题描述 投票:0回答:1

* {
  padding: 0;
  margin: 0;
}

.ground {
  display: flex;
  height: 500px;
  width: 700px;
  background-color: darkkhaki;
  margin: auto;
  margin-top: 70px;
}

.ball {
  align-self: flex-end;
  height: 50px;
  width: 50px;
  background-color: brown;
  border-radius: 50%;
  /* animation: name duration timing-function delay iteration-count direction fill-mode; */
  animation: bounce 1s cubic-bezier(0, 0, 0, 0.95) 1s infinite alternate forwards;
  -webkit-animation: bounce 1s cubic-bezier(0, 0, 0, 0.95) 1s infinite alternate forwards;
  animation: translation 5s ease-out 1s 1 normal forwards;
  -webkit-animation: translation 5s ease-out 1s 1 normal forwards;
}

@keyframes bounce {
  from {
    transform: translateY(0px);
  }
  to {
    transform: translateY(-400px);
  }
}

@-webkit-keyframes bounce {
  from {
    -webkit-transform: translateY(0px);
  }
  to {
    -webkit-transform: translateY(-400px);
  }
}

@keyframes translation {
  from {
    transform: translateX(0px);
  }
  to {
    transform: translateX(650px);
  }
}

@-webkit-keyframes translation {
  from {
    -webkit-transform: translateX(0px);
  }
  to {
    -webkit-transform: translateX(650px);
  }
}
<div class="ground">
  <div class="ball"></div>
</div>

在这段代码中,我尝试组合两个不同的动画来制作一个平移的球弹跳动画,但这些动画不是同时播放的,而是播放代码中稍后分配的动画。

我尝试将每个动画属性分开:

    animation-name: bounce, translation;
    animation-duration: 5s;
    animation-timing-function: cubic-bezier(0, 0, 0, 0.95), ease-out;
    animation-delay: 1s;
    animation-iteration-count: infinite, 1;
    animation-direction: alternate, normal;
    animation-fill-mode: forwards;

但它仍然不起作用,在这种情况下,我在弹跳动画之后提到了平移动画,所以只播放平移动画。

请帮我解决这个问题,因为我想同时播放两个动画,这样看起来球就在弹跳并朝某个方向移动。

html css animation css-animations
1个回答
0
投票

要实现球同时弹跳和水平移动的效果,需要正确组合弹跳和平移动画。原始代码中的问题是您正在为 .ball 定义两个单独的动画属性,而后一个属性会覆盖前者。要组合这些动画,您需要在动画速记属性中将它们一起列出,或者为两个动画单独定义每个动画属性。

以下是修改 CSS 以获得所需效果的方法:

* {
  padding: 0;
  margin: 0;
}

.ground {
  display: flex;
  height: 500px;
  width: 700px;
  background-color: darkkhaki;
  margin: auto;
  margin-top: 70px;
}

.ball {
  align-self: flex-end;
  height: 50px;
  width: 50px;
  background-color: brown;
  border-radius: 50%;
  
  /* Combining both animations */
  animation: bounce 1s cubic-bezier(0, 0, 0, 0.95) 1s infinite alternate,
             translation 5s ease-out 1s 1 normal forwards;
}

@keyframes bounce {
  0% {
    transform: translateY(0);
  }
  100% {
    transform: translateY(-400px);
  }
}

@keyframes translation {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(650px);
  }
}

要点:

  • 组合动画:.ball 的动画属性现在列出了两者 弹跳和平移动画。每个动画都由其定义 自己的持续时间、定时函数、延迟、迭代次数、方向和 填充模式。
  • 关键帧调整:确保关键帧设置正确 两个动画都准备好了。在这里,它们被定义为 0% 到 100%。
  • Transform 属性:组合两者使用的动画时 转换时,您需要确保它们不冲突。在这种情况下, 因为一个在 X 方向平移,另一个在 Y 方向平移 方向,它们可以毫无问题地组合。

通过以这种方式设置 CSS,两个动画应该同时运行,从而创建球同时弹跳和水平移动的效果。

© www.soinside.com 2019 - 2024. All rights reserved.