How to check String “green” is valid color or not in Jquery?

前端 未结 2 647
长情又很酷
长情又很酷 2021-01-18 23:17

I have scenario where user provide color name. For that I first need to check user provided color name is valid or not using jquery.

For example user can provide val

相关标签:
2条回答
  • 2021-01-18 23:29

    You can use following method to validate css color

    1. Create a temporary element
    2. Set any color using css('backgroundColor', 'white')
    3. After apply with the input value as backgroundColor using d.css('backgroundColor', this.value);
    4. Check the the color is changed or entered value is same that we are initially set, in that case it's a valid color

    $('#input').keyup(function() {
      if (this.value.trim()) {
        var d = $('<span/>')
          .css('backgroundColor', 'white')
          .css('backgroundColor', this.value);
        $('#op').html(this.value + (d.css('backgroundColor') == '' && this.value + (d.css('backgroundColor') != 'white' && d.css('backgroundColor') != 'rgb(255, 255, 255)') || /^white$/i.test(this.value) ? ' is valid' : ' is not valid'));
      } else
        $('#op').empty();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <input type="text" id="input">
    
    <div id="op"></div>

    0 讨论(0)
  • 2021-01-18 23:45

    You can set that color to any hidden test element(default color white) on page. then retrieve the color property from that element. if its other than white, then color is valid. else it is not.

    $('#testelement').css('background-color', colorstring);
    var coloris = !(/\d/.test(colorstring)) && (colorstring == "white" || $('#testelement').css('background-color') != "rgb(255, 255, 255)")   ? "valid" : "invalid";
    alert(colorstring +' is '+ coloris );
    
    0 讨论(0)
提交回复
热议问题