如何使用javascript更改进度条的颜色?

psj*_*j01 2 html javascript css jquery

到目前为止请查看我的代码(jsfiddle).

一旦达到最大容量,我试图改变进度条的颜色.

我怎么能做到这一点?

HTML代码:

<textarea></textarea>
<span id="characters">255 left</span>

<br>
<progress id="myProgress" value="0" max="255">
</progress>
Run Code Online (Sandbox Code Playgroud)

JS代码:

$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);

function updateCount() {
     var max = 255;
    var cs = $(this).val().length;
    document.getElementById("characters").innerHTML= max-cs + " left..";
    document.getElementById("myProgress").value = cs;
    if (event.which < 0x20) {
        return;
      }
    if (cs == max) {
        event.preventDefault();
        // make the color of progress bar red here!! 
      }     

}
Run Code Online (Sandbox Code Playgroud)

jaf*_*ech 7

添加progress::-webkit-progress-valuecss它会改变颜色并定义它jquery.

      if(cs>=max) 
      $('#myProgress').css("background-color", "red");
Run Code Online (Sandbox Code Playgroud)

或者您可以指定一个将分配背景颜色的类

      if(cs>=max) 
      $('#myProgress').addClass("red");
Run Code Online (Sandbox Code Playgroud)

$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);

function updateCount() {
	 var max = 255;
    var cs = $(this).val().length;
    if(cs>max) $(this).val($(this).val().toString().substring(0,max));
    document.getElementById("characters").innerHTML= max-cs + " left..";
    document.getElementById("myProgress").value = cs;
      if(cs>=max){
        $('#myProgress').addClass("red");
        }
      else{
        $('#myProgress').removeClass("red");

        }
    if (event.which < 0x20) {
        return;
      }
    if (cs >= max) {
        event.preventDefault();
        // make the color of progress bar red here!! 
      }     
      
}
Run Code Online (Sandbox Code Playgroud)
progress.red{
  background-color:red;
  color:red;
  }
progress.red[value] {color:red} /* IE10 */
progress.red::-webkit-progress-bar-value {background-color:red}
progress.red::-webkit-progress-value {background-color:red}
progress.red::-moz-progress-bar {background-color:red}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea></textarea>
<span id="characters">255 left</span>

<br>
<progress id="myProgress" value="0" max="255">
</progress>
Run Code Online (Sandbox Code Playgroud)