【问题标题】:Only one CSS animation bar at any point of time任何时候都只有一个 CSS 动画栏
【发布时间】:2019-05-06 08:40:23
【问题描述】:
我正在使用 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>
【问题讨论】:
标签:
html
css
css-animations
linear-gradients
【解决方案1】:
不要制作渐变50%,而是制作200%,并在其中定义2个渐变颜色。这样做渐变的每个部分将准确覆盖元素宽度的100%,然后您可以从左到右对其进行动画处理。
.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>