【问题标题】:CSS animation not behaving as expectedCSS 动画未按预期运行
【发布时间】:2020-03-27 03:15:13
【问题描述】:
问题
我制作了一个简单的 css 动画,但它的行为与我预期的不同。
这个想法是让动画画一条直线(从上向下),然后消失(也从上向下)。
随着动画的开始,线的起点向下移动一点,然后再次向上移动以保持在设定的位置(动画结束时的底部也是如此)。
问题
如何让线的起点保持在一个位置,而不是上下“弹跳”?
预期行为
实际行为
代码
.lineWrapper {
width: 1px;
height: 300px;
margin: auto;
position: relative;
}
.lineWrapper .line {
width: 100%;
height: 100%;
background: #000;
animation: scrollLine 5s linear infinite;
}
@keyframes scrollLine {
0% {
transform: scaleY(0);
}
10% {
transform: scaleY(0);
transform-origin: top;
}
30% {
transform: scaleY(1);
}
70% {
transform: scaleY(1);
}
90% {
transform: scaleY(0);
transform-origin: bottom;
}
100% {
transform: scaleY(0);
}
}
<div class="lineWrapper">
<div class="line"></div>
</div>
代码笔
https://codepen.io/strazan/pen/RwPYgjq
【问题讨论】:
标签:
html
css
css-animations
css-transitions
【解决方案1】:
默认transform-origin 是中心,所以如果你在初始和最后一个状态中省略它,它将被设置为中心。您还需要立即更改中间的transform-origin:
.lineWrapper {
width: 1px;
height: 300px;
margin: auto;
position: relative;
}
.line {
height: 100%;
background: #000;
animation: scrollLine 5s infinite;
}
@keyframes scrollLine {
0%,10% {
transform: scaleY(0);
transform-origin: top;
}
49.9% {
transform: scaleY(1);
transform-origin: top;
}
50% {
transform: scaleY(1);
transform-origin: bottom;
}
90%,100% {
transform: scaleY(0);
transform-origin: bottom;
}
}
<div class="lineWrapper">
<div class="line"></div>
</div>
【解决方案2】:
我用一些不同的代码行制作了类似的 CSS 动画。
body {
margin: 0px;
display: flex;
justify-content: center;
background: black;
overflow: hidden;
}
.line-wrapper {
height: 800px;
width: 8px;
background: tranparent;
display: flex;
justify-content: center;
animation: down 2s linear infinite;
}
@keyframes down {
0% {
transform: translateY(0px);
}
15% {
transform: translateY(0px);
}
30% {
transform: translateY(0px);
}
60% {
transform: translateY(90px);
}
90% {
transform: translateY(115px);
}
100% {
transform: translateY(115px);
}
}
.line {
height: 8px;
width: 4px;
background: Gray;
animation: scrollLine 2s ease-in-out infinite;
}
@keyframes scrollLine {
100% {
height: 800px;
}
}
.eraser {
height: 0px;
width: 4px;
background: black;
animation: rmv 2s linear infinite;
}
@keyframes rmv {
55% {
height: 0px;
}
100% {
height: 800px;
}
}
<div class="line-wrapper">
<div class="line">
<div class="eraser"></div>
</div>
</div>