CSS 动画未按预期运行

问题

我制作了一个简单的 css 动画,但它的行为并不符合我的预期。这个想法是让动画绘制一条直线(从上向下),然后消失(也是从上向下)。

当动画开始时,线的起点向下移动一点,然后再次向上移动以保持在设定位置(动画结束时的底部也是如此)。

问题

如何让线条的起点停留在一个位置而不是上下“弹跳”?

预期行为

https://i.stack.imgur.com/NoHZt.gif

实际行为

https://i.stack.imgur.com/vqjoU.gif


代码

.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


慕田峪9158850
浏览 97回答 2
2回答

catspeake

默认值为transform-origin居中,因此如果您在初始和最后状态中省略它,它将被设置为居中。您还需要立即更改transform-origin中间的内容:.lineWrapper {&nbsp; width: 1px;&nbsp; height: 300px;&nbsp; margin: auto;&nbsp; position: relative;}.line {&nbsp; height: 100%;&nbsp; background: #000;&nbsp; animation: scrollLine 5s infinite;}@keyframes scrollLine {&nbsp; 0%,10% {&nbsp; &nbsp; transform: scaleY(0);&nbsp; &nbsp; transform-origin: top;&nbsp; }&nbsp; 49.9% {&nbsp; &nbsp; transform: scaleY(1);&nbsp; &nbsp; transform-origin: top;&nbsp; }&nbsp; 50% {&nbsp; &nbsp; transform: scaleY(1);&nbsp; &nbsp; transform-origin: bottom;&nbsp; }&nbsp; 90%,100% {&nbsp; &nbsp; transform: scaleY(0);&nbsp; &nbsp; transform-origin: bottom;&nbsp; }}<div class="lineWrapper">&nbsp; <div class="line"></div></div>

翻阅古今

我用一些不同的代码行制作了类似的 CSS 动画。body {&nbsp; margin: 0px;&nbsp; display: flex;&nbsp; justify-content: center;&nbsp; background: black;&nbsp; overflow: hidden;}.line-wrapper {&nbsp; height: 800px;&nbsp; width: 8px;&nbsp; background: tranparent;&nbsp; display: flex;&nbsp; justify-content: center;&nbsp; animation: down 2s linear infinite;}@keyframes down {&nbsp; 0% {&nbsp; &nbsp; transform: translateY(0px);&nbsp; }&nbsp; 15% {&nbsp; &nbsp; transform: translateY(0px);&nbsp; }&nbsp; 30% {&nbsp; &nbsp; transform: translateY(0px);&nbsp; }&nbsp; 60% {&nbsp; &nbsp; transform: translateY(90px);&nbsp; }&nbsp; 90% {&nbsp; &nbsp; transform: translateY(115px);&nbsp; }&nbsp; 100% {&nbsp; &nbsp; transform: translateY(115px);&nbsp; }}.line {&nbsp; height: 8px;&nbsp; width: 4px;&nbsp; background: Gray;&nbsp; animation: scrollLine 2s ease-in-out infinite;}@keyframes scrollLine {&nbsp; 100% {&nbsp; &nbsp; height: 800px;&nbsp; }}.eraser {&nbsp; height: 0px;&nbsp; width: 4px;&nbsp; background: black;&nbsp; animation: rmv 2s linear infinite;}@keyframes rmv {&nbsp; 55% {&nbsp; &nbsp; height: 0px;&nbsp; }&nbsp; 100% {&nbsp; &nbsp; height: 800px;&nbsp; }}<div class="line-wrapper">&nbsp; <div class="line">&nbsp; &nbsp; <div class="eraser"></div>&nbsp; </div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5