我正在尝试更改按钮的关键帧动画,以将某些内容从div的底部移动到顶部。当我使用底部动画时:
@keyframes moveUpWithFade2 {
from {
bottom: 0%;
opacity: 0;
}
10% {
opacity: 1;
}
50% {
opacity: 1;
}
to {
bottom: 100%;
opacity: 0;
}
}
它会从父div的底部逐渐淡入顶部。但是,如果我使用transform:translateY(100%)
,它将在我尝试设置动画的div维度上运行。因此,如果我有一个高度为25px的矩形,那么它将向上移动25px。因此,为了获得与底部相同的行为,我需要指定translateY的很高的值,如下所示:
@keyframes moveUpWithFade {
from {
transform: translateY(0%);
opacity: 0;
}
10% {
transform: translateY(-200%);
opacity: 1;
}
50% {
transform: translateY(-1000%);
opacity: 1;
}
to {
transform: translateY(-2000%);
opacity: 0;
}
}
.parent {
width: 25px;
height: 400px;
}
.rect {
position: absolute;
width: 25px;
height: 25px;
background-color: skyblue;
}
.movingDiv {
bottom: 0;
animation: moveUpWithFade 6s linear infinite forwards, animateX 2s ease-in-out 3 alternate;
overflow: hidden;
}
@keyframes moveUpWithFade {
from {
transform: translateY(0%);
opacity: 0;
}
10% {
transform: translateY(-200%);
opacity: 1;
}
50% {
transform: translateY(-1000%);
opacity: 1;
}
to {
transform: translateY(-2000%);
opacity: 0;
}
}
@keyframes moveUpWithFade2 {
from {
bottom: 0%;
opacity: 0;
}
10% {
opacity: 1;
}
50% {
opacity: 1;
}
to {
bottom: 100%;
opacity: 0;
}
}
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translateY -->
<div class="parent">
<div class="rect movingDiv">Moving</div>
</div>
在我的情况下,我向上或向下移动的对象的大小是可变的,而不是硬编码的。有没有办法使用在父div高度上运行的transform属性来操纵子div?
答案 0 :(得分:1)
考虑一个额外的元素,您将在其中应用变换动画并使它与父对象的高度相同:
.parent {
width: 25px;
height: 300px;
border: 2px solid;
overflow:hidden;
}
.rect {
width: 25px;
height: 25px;
background-color: skyblue;
transform:translateY(-100%);
}
.movingDiv {
height:100%;
animation: moveUpWithFade 6s linear infinite;
}
@keyframes moveUpWithFade {
from {
transform: translateY(100%);
opacity: 0;
}
10% {
transform: translateY(80%);
opacity: 1;
}
50% {
transform: translateY(30%);
opacity: 1;
}
to {
transform: translateY(0%);
opacity: 0;
}
}
<div class="parent">
<div class="movingDiv">
<div class="rect ">Moving</div>
</div>
</div>