JS onKeyup Counter-当他变成负数时如何更改计数器的颜色?

时间:2018-09-26 23:15:14

标签: javascript colors

$(function(){

        function limitaCaracteres(input, counter, limit){
          $('.'+counter).text(limit+' restantes');
          var left;
          $('.'+input).on('keyup', function(e){
            var qtdCaracteres = $(this).val().length;
            left = limit-qtdCaracteres;
            $('.'+counter).text(left+' restantes');

          });
        }
        limitaCaracteres('text1', 'count1', 10);
      });
<!doctype html>
<html>
  <head>
    <title></title>
  </head>
  <body style="background-color: #EAEAEA;">
      <input type="text" name="title" class="input100 text1" autocomplete="off" required>     
      <span class="focus-input100" data-placeholder="Title"></span>
      <span class="count1"></span>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    </body>
</html>

我想更改计数器的颜色,最初的颜色应该是绿色,当计数器变为负数时,颜色应该是红色。

示例:

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以按以下方式使用:

    $(function(){

function limitaCaracteres(input, counter, limit){
  $('.'+counter).text(limit+' restantes');
  var left;
  $('.'+input).on('keyup', function(e){
    var qtdCaracteres = $(this).val().length;
    left = limit-qtdCaracteres;
   
    $('.'+counter).text(left+' restantes');
    if(left<0){
        $('.'+counter).removeClass("positive");
        $('.'+counter).addClass("negative");
    }else{
        $('.'+counter).removeClass("negative");
        $('.'+counter).addClass("positive");
    }

  });
}
limitaCaracteres('text1', 'count1', 10);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
    <title></title>
    <style>
    .negative{
        color: red;
    }
    .positive{
        color: greenyellow;
    }
    </style>
  </head>
  <body style="background-color: #EAEAEA;">
      <input type="text" name="title" class="input100 text1" autocomplete="off" required>     
      <span class="focus-input100" data-placeholder="Title"></span>
      <span class="count1 positive"></span>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
</body>