如何根据百分比创建颜色更改的进度条

时间:2017-09-13 01:06:50

标签: javascript php html css

如何根据百分比创建颜色更改的进度条 我想根据给定的值(js& css)改变条形颜色以便顺利改变

例如:0%=绿色,100%=红色,75%=橙色(红色和绿色之间的渐变) 这段代码在css中:

<style>
#myBar {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: #ff0000;
    text-align: center;
    line-height: 30px;
    color: white;
    border-radius: 1em;
    animation: color 2s linear 0s alternate;
}

@keyframes color{
    0% {background-color: #0f0;}
    50% {background-color: #ff0;}
    100% {background-color: #f00;}
}
</style>

此文件中的代码为index.php:

<script>
function move() {
    var elem = document.getElementById("myBar");
    var newElem = document.getElementById("percent");
    var height = 1;
    score = <?php echo($percentation);?>;
    var id = setInterval(frame, 25);

    function frame() {
        if (height >= score) {
            clearInterval(id);
        } else {
            height++;
            elem.style.height = height + '%';
            newElem.innerHTML = height + '%';
        }
    }
}
</script>

myBar是加载栏本身的div %是div以输出值

1 个答案:

答案 0 :(得分:2)

你可以做纯CSS。这是一个例子

&#13;
&#13;
.progressBar {
  background-color: lightgrey;
  width: 200px;
  height: 20px;
  
}


.progress {
    width: 10%;
    height: 100%;
    background-color: blue;
    animation: color 5s linear 0s alternate;
}

@keyframes color{
    10% {
    background-color: #0f0;
    width: 20%;/*At 10%, change the width to 20%*/
    }
    40% {
    background-color: #ff0;
    width: 40%;
    }
    70% {
    background-color: #f00;
    width: 60%;
    }
    100% {
    background-color: #fff;
    width: 100%;
    }
}
&#13;
<div class="progressBar">
    <div class="progress">
    
    </div>
</div>
&#13;
&#13;
&#13;

这个想法是什么?您可以通过关键帧更改宽度或高度。

这是一个使用高度的例子,就像你问的那样。

&#13;
&#13;
.progressBar {
  background-color: lightgrey;
  width: 20px;
  height: 200px;
  
}


.progress {
    width: 100%;
    height: 10%;
    background-color: blue;
    animation: color 5s linear 0s alternate;
}

@keyframes color{
    10% {
    background-color: #0f0;
    height: 20%;/*At 10%, change the height to 20%*/
    }
    40% {
    background-color: #ff0;
    height: 40%;
    }
    70% {
    background-color: #f00;
    height: 60%;
    }
    100% {
    background-color: #fff;
    height: 100%;
    }
}
&#13;
<div class="progressBar">
    <div class="progress">
      
    </div>
</div>
&#13;
&#13;
&#13;