在任何时间点只有一个 CSS 动画条

Only one CSS animation bar at any point of time

我正在使用 CSS 动画来显示不确定的进度条。参考下面的代码。如果您注意到在任何时间点有 2 个移动渐变,即当第一个达到宽度的 50% 时,第二个开始。我知道我已经使用 webkit-background-size(50% 和 100%)以这种方式定义了 css。然而,我无法做的是确保在任何时间点都应该只有 1 个移动部分 - 即一旦动画到达 div 的右端,那么它应该从左端开始.对此有任何指示吗?

参考https://jsfiddle.net/AnuragSinha/nuokygpe/1/和下面相应的代码。

    @-webkit-keyframes moving-gradient {
    0% { background-position: left bottom; }
    100% { background-position: right bottom; }
    }
    
    .loading-gradient {
    width: 200px;
    height: 30px;
    background: -webkit-linear-gradient(
            left,
            #e9e9e9  50%,
            #eeefef 100%
        ) repeat;
    -webkit-background-size: 50% 100%;
    -webkit-animation-name: moving-gradient;
    -webkit-animation-duration: 1s;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-timing-function: linear;
    }
<div class="loading-gradient" style="width: 200px; height: 30px"> </div>
   

不是制作渐变50%而是制作200%并在其中定义2种渐变着色。这样做渐变的每个部分将完全覆盖元素宽度的 100% 然后你可以从左到右动画它。[=​​18=]

.loading-gradient {
  width: 200px;
  height: 30px;
  background: linear-gradient(to left, 
    #e9e9e9 0%  25%, #eeefef 50%,   /* first one take the half*/
    #e9e9e9 50% 75%, #eeefef 100%); /* second one take the other half*/
  background-size: 200% 100%;
  animation: moving-gradient 1s linear infinite;
}

@keyframes moving-gradient {
  0% {
    background-position: right;
  }
 /*100% {
    background-position: left; /* No need to define this since it's the default value*/
  }*/
}
<div class="loading-gradient" style="width: 200px; height: 30px"> </div>

由于渐变现在的尺寸大于容器,您需要制作相反的动画(从右到左)。

更多详情:Using percentage values with background-position on a linear gradient


这是另一个可以考虑伪元素和翻译动画的想法:

.loading-gradient {
  width: 200px;
  height: 30px;
  position:relative;
  z-index:0;
  overflow:hidden;
}
.loading-gradient:before {
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  right:0;
  width:200%;
  bottom:0;
  background: linear-gradient(to left, #e9e9e9 50%, #eeefef 100%);
  background-size: 50% 100%;
  animation: moving-gradient 1s linear infinite;
}

@keyframes moving-gradient {
  100% {
    transform: translate(50%);
  }
}
<div class="loading-gradient" style="width: 200px; height: 30px"> </div>