Css加载条改变颜色

时间:2017-06-28 11:10:51

标签: html css animation

到目前为止,我有一个简单的加载栏:

setInterval(tick, 10);
var width = 0;
function tick() {
    var el = document.getElementById('bar_full');
    width += 1;
    width = width > 97 ? 97 : width;
    document.getElementById('bar_full').style.width = width + '%';
}
#bar_shell {
    width: 100%;
    height: 30px;
    background: lightGray;
    border-radius: 20px;
}

#bar_full {
    width: 0%;
    margin-top: 5px;
    margin-left: 5px;
    height: 20px;
    background: green;
    position: absolute;
    border-radius: 10px;
}
<div id="bar_shell">
    <div id="bar_full"></div>
</div>

然而,我希望它能在颜色上升时改变颜色。例如,当它是10%时,它将是深绿色,50%时它将开始变黄,而100%时它将变为红色。我想用css解决这个问题,但接受了js。感谢。

2 个答案:

答案 0 :(得分:3)

根据宽度设置背景颜色。一种方法是使用具有百分比和伴随颜色的对象:

setInterval(tick, 10);
var width = 0;
var colors = {
  '0': '#cfeff0',
  '10': '#bbc6ce',
  '50': '#660066',
  '80': '#f6546a'
};
function tick() {
    var el = document.getElementById('bar_full');
    width += 1;
    width = width > 97 ? 97 : width;
    var el = document.getElementById('bar_full');
    el.style.width = width + '%';
    var color = colors[width];
    if (color) el.style.backgroundColor = color;
}
#bar_shell {
    width: 100%;
    height: 30px;
    background: lightGray;
    border-radius: 20px;
}

#bar_full {
    width: 0%;
    margin-top: 5px;
    margin-left: 5px;
    height: 20px;
    background: green;
    position: absolute;
    border-radius: 10px;
}
<div id="bar_shell">
    <div id="bar_full"></div>
</div>

答案 1 :(得分:3)

您可以使用关键帧来使用Css annimation,请参阅下面的代码段:

将动画填充模式设置为forwards以保持最终的动画状态。

&#13;
&#13;
#bar_shell {
    width: 100%;
    height: 30px;
    background: lightGray;
    border-radius: 20px;
}

#bar_full {
    width: 0%;
    margin-top: 5px;
    margin-left: 5px;
    height: 20px;
    background: green;
    position: absolute;
    border-radius: 10px;
    -webkit-animation: changecolor 5s forwards; /* Safari 4.0 - 8.0 */
    animation: changecolor 5s forwards;
    animation-timing-function: ease-in-out;
    -webkit-animation-timing-function: ease-in-out;
}


@-webkit-keyframes changecolor {
    0%   {width: 0; background:blue}
    25%  {width: 25%;background:yellow}
    50%  {width: 50%;background:orange}
    75% {width: 75%;background:red}
    100% {width: 100%;color:green}
}

/* Standard syntax */
@keyframes changecolor {
    0%   {width: 0; background:blue}
    25%  {width: 25%;background:yellow}
    50%  {width: 50%;background:orange}
    75% {width: 75%;background:red}
    100% {width: 97%;background:green}
}
&#13;
<div id="bar_shell">
    <div id="bar_full"></div>
</div>
&#13;
&#13;
&#13;