简体   繁体   中英

How do I change the css gradient values when my progress bar value changes?

In my CSS file I have the following code (for Google Chrome) that styles the progress bar with a gradient effect.

progress[value] {
    width: 100%; height: 40px;
    margin: 0 0 3em;
    border: 4px solid #000000;
}

progress::-webkit-progress-value {
    background-image:

    -webkit-linear-gradient(-45deg,
                           transparent 33%, rgba(0, 0, 0, .1) 44%,
                           rgba(0,0, 0, .1) 66%, transparent 66%),
    -webkit-linear-gradient(top,
                           rgba(255, 255, 255, .25),
                           rgba(0, 0, 0, .25)),
    -webkit-linear-gradient(right, #04d647, #009999);
}

However my JavaScript code causes my progress bar to constantly change values. Right now the gradient color is set to a green gradient, but I would like to change the color based on how high the value is (ie less than 30% = red gradient, less than 65% but more than 30% = yellow gradient, and more than 65% = green gradient).

I have this JavaScript code to start off with in my HTML file, but I don't know how I would go about changing the colors in progress::-webkit-progress-value depending on what the value is, because I don't know how I would use the webkit-progress as a tag.

if (progressbar1.value >= .30) {

   $("progress::-webkit-progress-value").css("background-color", "#424242");
   // something like this^^....what tags/scripts go here??

}   

What am I doing wrong?

Add a data attribute to your progress tag, which will hold the values you want to change the gradient at:

<progress data-value="0">

Then, in your JavaScript, check the value of the progress bar and, if it's over a value that you want to change the gradient at, update the data attribute:

if(progressbar1.value>=65)
    progressbar1.dataset.value=65
else if(progressbar1.value>=30)
    progressbar1.dataset.value=30
else
    progressbar1.dataset.value=0

Finally, in your CSS, use attribute selectors to set the rules for each value of the data-value attribute, changing the gradient and/or whatever other styles you want:

progress[data-value="0"]::-webkit-progress-value{
    background-image:/* red gradient here */;
}
progress[data-value="30"]::-webkit-progress-value{
    background-image:/* yellow gradient here */;
}
progress[data-value="65"]::-webkit-progress-value{
    background-image:/* green gradient here */;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM