CSS线性渐变进度动画

问题描述 投票:0回答:1

我制作了一个动画,指示倒计时直到吐司通知消失:

.toastDiv {
  animation: toastProgress 3s ease;
  border: 1px solid rgba(0, 0, 0, .5);
  border-radius: 5px;
  box-shadow: 0 0 5px 0 rgba(0, 0, 0, .25);
  margin: 0 0 1ex 0;
  padding: 1ex 1em;
}

@keyframes toastProgress {
  0% {
    background: linear-gradient(to right, aliceblue 0%, aliceblue 0%, white 0%, white 100%);
  }
  10% {
    background: linear-gradient(to right, aliceblue 0%, aliceblue 10%, white 10%, white 100%);
  }
  20% {
    background: linear-gradient(to right, aliceblue 0%, aliceblue 20%, white 20%, white 100%);
  }
  30% {
    background: linear-gradient(to right, aliceblue 0%, aliceblue 30%, white 30%, white 100%);
  }
  40% {
    background: linear-gradient(to right, aliceblue 0%, aliceblue 40%, white 40%, white 100%);
  }
  50% {
    background: linear-gradient(to right, aliceblue 0%, aliceblue 50%, white 50%, white 100%);
  }
  60% {
    background: linear-gradient(to right, aliceblue 0%, aliceblue 60%, white 60%, white 100%);
  }
  70% {
    background: linear-gradient(to right, aliceblue 0%, aliceblue 70%, white 70%, white 100%);
  }
  80% {
    background: linear-gradient(to right, aliceblue 0%, aliceblue 80%, white 80%, white 100%);
  }
  90% {
    background: linear-gradient(to right, aliceblue 0%, aliceblue 90%, white 90%, white 100%);
  }
  100% {
    background: linear-gradient(to right, aliceblue 0%, aliceblue 100%, white 100%, white 100%);
  }
}
<div class="toastDiv">hello</div>

但是,必须阐明各个动画阶段是非常乏味的,而且按照我选择的粒度,我得到的结果不稳定。

我尝试使用这个:

@keyframes toastProgress {
  from {
    background: linear-gradient(to right, aliceblue 0%, aliceblue 0%, white 0%, white 100%);
  }
  to {
    background: linear-gradient(to right, aliceblue 0%, aliceblue 100%, white 100%, white 100%);
  }
}

但这会从一个纯色背景过渡到下一个背景,而不是从左到右对颜色停止进行动画处理。

有没有办法只使用

from
to
而不是百分比步长来制作这种进度式渐变动画?

css css-animations linear-gradients
1个回答
2
投票

您可以依靠

background-size
动画和
steps()
,如下所示:

.toastDiv {
  border: 1px solid rgba(0, 0, 0, .5);
  border-radius: 5px;
  box-shadow: 0 0 5px 0 rgba(0, 0, 0, .25);
  margin: 0 0 1ex 0;
  padding: 1ex 1em;
  background:
    linear-gradient(aliceblue 0 0) left no-repeat,
    white;
  animation: toastProgress 5s steps(10,jump-none); 
}

@keyframes toastProgress {
  0% {
    background-size:0% 100%;
  }
  100% {
    background-size:100% 100%;
  }
}
<div class="toastDiv">hello</div>

<div class="toastDiv" style="animation-timing-function:ease">without Steps</div>

与了解

steps()
如何工作相关:https://stackoverflow.com/a/51843473/8620333

© www.soinside.com 2019 - 2024. All rights reserved.