* {
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;
但它仍然不起作用,在这种情况下,我在弹跳动画之后提到了平移动画,所以只播放平移动画。
请帮我解决这个问题,因为我想同时播放两个动画,这样看起来球就在弹跳并朝某个方向移动。
要实现球同时弹跳和水平移动的效果,需要正确组合弹跳和平移动画。原始代码中的问题是您正在为 .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);
}
}
要点:
通过以这种方式设置 CSS,两个动画应该同时运行,从而创建球同时弹跳和水平移动的效果。