【问题标题】:CSS linear gradient progress animationCSS 线性渐变进度动画
【发布时间】:2020-03-27 21:28:16
【问题描述】:

我已经制作了一个动画,它指示倒计时,直到 toast 通知消失:

.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%);
  }
}

但这会从一个纯色背景过渡到下一个纯色背景,而不是从左到右为颜色停止设置动画。

有没有办法只使用 fromto 而不是百分比步长来制作这种进度样式的渐变动画?

【问题讨论】:

    标签: css css-animations linear-gradients


    【解决方案1】:

    您可以依赖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,aliceblue) left no-repeat,
        white;
      animation: toastProgress 5s steps(10,start); 
    }
    
    @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://*.com/a/51843473/8620333

    【讨论】: