我在摆弄3D CSS动画,遇到了一个问题,我有一个正在X轴上平移的移动元素。此转换持续2秒。但是,我也想对Y轴上的元素应用旋转,该旋转持续30秒。
我遇到的问题是,由于translate和rotate都是CSS中transform属性的一部分,所以似乎没有一种方法可以对它们分别应用不同的定时。
.ball {
position: absolute;
left: 50%;
top: 50%;
width: 50px;
height: 50px;
border-radius: 50%;
background-color: red;
animation: animate 2s infinite linear;
}
@keyframes animate {
to {
transform: translateX(100px) rotateY(360deg);
}
}
<html>
<body>
<div class="ball"></div>
</body>
</html>
正如你所看到的,我可以让球同时平移和旋转,但我不知道如何对每个动画应用单独的计时。同样,我希望平移是2秒的动画,但旋转是30秒的动画。这可能吗?
由于转换是一个单独的属性,因此必须使用包装器:
.ball {
position: absolute;
left: 50%;
top: 50%;
width: 50px;
height: 50px;
border-radius: 50%;
background: linear-gradient(0deg, rgba(171,17,121,1) 0%, rgba(17,171,154,1) 100%);
animation: animate2 .5s infinite linear;
}
.ballWrapper {
animation: animate 2s infinite linear;
}
@keyframes animate {
to {
transform: translateX(200px);
}
}
@keyframes animate2 {
to {
transform: rotateY(360deg);
}
}
<body>
<div class="ballWrapper">
<div class="ball"></div>
</div>
</body>
控制角度以提高或降低旋转速度。我使用calc()
来轻松地将旋转表示为N*360deg
,但您可以手动设置您想要的值
.ball {
position: absolute;
left: 50%;
top: 50%;
width: 50px;
height: 50px;
border-radius: 50%;
background-color: red;
animation: animate 2s infinite linear;
}
@keyframes animate {
to {
transform: translateX(100px) rotateY(calc(3*360deg));
}
}
<html>
<body>
<div class="ball"></div>
</body>
</html>
虽然可以将所有动画放在一个动画中,但这会非常混乱,而且不太灵活,因为如果要更改2秒或30秒,%s需要重新计算。
如果您不想或不能更改HTML,可以将转换应用于div,并将旋转应用于after-pseudo元素。
.ball {
position: absolute;
left: 50%;
top: 50%;
width: 50px;
height: 50px;
animation: move 30s infinite linear;
}
.ball::after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border-radius: 50%;
background-color: red;
animation: animate 2s infinite linear;
z-index: 1;
}
@keyframes animate {
to {
transform: rotateY(360deg);
}
}
@keyframes move {
to {
transform: translateX(100px);
}
}
<html>
<body>
<div class="ball"></div>
</body>
</html>