如何检查字符串“绿色”是否在Jquery中是否有效?

我有用户提供颜色名称的场景。 为此我首先需要检查用户提供的颜色名称是否有效使用jquery。

例如,用户可以提供橙色值,ornge拼写错误。

怎么检查

任何帮助对我来说都是最好的。

您可以使用以下方法来validationcss颜色

  1. 创建一个临时元素
  2. 使用css('backgroundColor', 'white')设置任何颜色css('backgroundColor', 'white')
  3. 使用d.css(’backgroundColor’,this.value)将输入值作为backgroundColor应用之后;
  4. 检查颜色是否已更改或输入的值与我们最初设置的值相同,在这种情况下它是有效颜色
 $('#input').keyup(function() { if (this.value.trim()) { var d = $('') .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(); }); 
   

您可以将该颜色设置为页面上任何隐藏的测试元素(默认颜色为白色)。 然后从该元素中检索color属性。 如果它不是白色,那么颜色是有效的。 否则它不是。

 $('#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 );