减少CSS动画中的元素高度会稍微延迟。为什么呢?

时间:2017-06-13 01:24:52

标签: html css animation height dimension

默认情况下,CSS动画会在页面加载时立即运行,但可以使用animation-delay属性延迟它们。运行以下代码段时,矩形不会垂直收缩,直到几秒钟后才会过去。

为什么它会像这样“等待”,我该如何解决?

/* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ INITIAL /////////////////////////////// */

html,
body {
  height: 100%;
}

body {
  display: flex;
  margin: 0;
  font-family: sans-serif;
}

p {
  overflow: hidden;
  max-height: 100rem;
  width: 10rem;
  margin: auto;
  padding: 4rem 1rem;
  background-color: #f8f8f8;
  color: #222;
  text-align: center;
}

/* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ANIMATIONS ///////////////////////////// */

.contract-ht {
  animation-name: contract-height;
  animation-duration: 2s;
  animation-fill-mode: forwards;
}

@keyframes contract-height {
  100% {
    max-height: 0;
  }
}
<p class="contract-ht">shrink me vertically</p>

编辑:我在高度动画旁边添加了一个带缩放变换的片段,因此可以看到高度动画的开始速度比scale动画慢得多。最左边的动画几乎从右边完成开始。我希望左派在右翼同时明显开始萎缩。它们都具有相同的持续时间,为什么基于max-height的动画会在我不使用animation-delay时延迟?

以下代码段

/* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ INITIAL /////////////////////////////// */

html,
body {
  height: 100%;
}

body {
  display: flex;
  margin: 0;
  font-family: sans-serif;
}

p {
  overflow: hidden;
  max-height: 100rem;
  width: 10rem;
  margin: auto;
  padding: 4rem 1rem;
  background-color: #f8f8f8;
  color: #222;
  text-align: center;
}

/* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ANIMATIONS ///////////////////////////// */

.contract-ht {
  animation-name: contract-height;
  animation-duration: 2s;
  animation-fill-mode: forwards;
}

@keyframes contract-height {
  100% {
    max-height: 0;
  }
}

/* added these two css rules below */
.scale-ht {
  animation-name: scale-height;
  animation-duration: 2s;
  animation-fill-mode: forwards;
}

@keyframes scale-height {
  100% {
    transform: scaleY( 0 );
  }
}
<p class="contract-ht">shrink me vertically</p>

<!-- added the element below -->
<p class="scale-ht">scale my height</p>

1 个答案:

答案 0 :(得分:0)

因为你已经给了animation-duration: 2s;因此需要2秒才能完成100%的过渡。只需减少它如下,以减少延迟。如果您删除转换持续时间,它将显示立即结果

&#13;
&#13;
/* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ INITIAL /////////////////////////////// */

html,
body {
  height: 100%;
}

body {
  display: flex;
  margin: 0;
  font-family: sans-serif;
}

p {
  overflow: hidden;
  max-height: 100rem;
  width: 10rem;
  margin: auto;
  padding: 4rem 1rem;
  background-color: #f8f8f8;
  color: #222;
  text-align: center;
}

/* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ANIMATIONS ///////////////////////////// */

.contract-ht {
  animation-name: contract-height;
  animation-fill-mode: forwards;
}

@keyframes contract-height {
  100% {
    max-height: 0;
  }
}
&#13;
<p class="contract-ht">shrink me vertically</p>
&#13;
&#13;
&#13;