我有两个盒子:
<div class='item' style='transform:translateY(100px)'>
</div>
<div class='item' style='transform:translateY(300px)'>
</div>
他们都使用同一个类:
.item {
position:absolute;
background:red;
animation:float 3s ease-in-out infinite;
width:100px;
height:100px;
}
动画看起来像:
@keyframes float {
from, to { transform: translateY(-10px); }
50% { transform: translateY(10px); }
}
但这会使两个框都在 -10 到 10 像素之间。我想要的是它相对于框的当前值。
所以在 y:100px 的 box1 会从 90px 到 110px 动画 y:300px 的 box2 将从 290px 到 310px 动画
是否可以在 css 中执行此操作?我宁愿每个盒子都没有特定的动画。因为我可能有数百个盒子。
jsfiddle: https://jsfiddle.net/foreyez/1n1en8uk/
这表明在动画点,两个盒子都在同一个地方......但如果是相对动画,它们只会在当前位置上下 float 。
注意:请不要使用 top/left 来获取相对位置我正在寻找专门用于相对 TRANSFORMS 的位置。 (如果您一定知道为什么我在 3d 中对 z 轴执行此操作,因为已经使用了 x,y)。
最佳答案
您可以将.item
元素的position
设置为relative
;使用 :nth-of-type()
伪选择器将每个元素的 top
属性设置为元素应在 20px< 之间设置动画的初始位置
相对于其 .item
兄弟的范围。
.item {
position: relative;
background: red;
animation: float 3s infinite ease-in-out;
width: 100px;
height: 100px;
}
.item:nth-of-type(1) {
top: 100px;
}
.item:nth-of-type(2) {
top: 300px;
}
@keyframes float {
from, to {
transform: translateY(-10px);
}
50% {
transform: translateY(10px);
}
}
<div class="item">
</div>
<div class="item">
</div>
jsfiddle https://jsfiddle.net/1n1en8uk/3/
关于javascript - 如何使用 css 中的相对变换制作动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39606732/