简体   繁体   English

如何使用javascript / jquery知道给定的字符串是否为hex,rgb,rgba或hsl颜色?

[英]How can I know if a given string is hex, rgb, rgba or hsl color using javascript/jquery?

I used regex for the hex. 我用十六进制的正则表达式。 /^\\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/ but I dont know what I should for do for finding rgb, rgba and hsl. /^\\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/但我不知道应该怎样做才能找到rgb,rgba和hsl。 I am getting the input in string. 我在字符串中获取输入。 For example, the input will contain "rgb(0,0,0)"or "rgb(0,0,0,0.2)". 例如,输入将包含“rgb(0,0,0)”或“rgb(0,0,0,0.2)”。

There are different options here: 这里有不同的选择:

1. Use a dummy element 1.使用虚拟元素

Use the browser's validation. 使用浏览器的验证。 Create a dummy HTML element, assign the color and check if it's set. 创建一个虚拟 HTML元素,分配颜色并检查它是否已设置。 This is by far the best option. 这是迄今为止最好的选择。 It's not only easier, but it will also allow forward compatibility. 它不仅更容易,而且还允许向前兼容。

function CheckValidColor(color) {
    var e = document.getElementById('divValidColor');
    if (!e) {
        e = document.createElement('div');
        e.id = 'divValidColor';
    }
    e.style.borderColor = '';
    e.style.borderColor = color;
    var tmpcolor = e.style.borderColor;
    if (tmpcolor.length == 0) {
        return false;
    }
    return true;
}

// function call
var inputOK = CheckValidColor('rgb( 0, 0, 255)');

This will return true for all colors accepted by the browser, even in cases you may consider invalid. 对于浏览器接受的所有颜色,这将返回true ,即使在您认为无效的情况下也是如此。


2. Capture the numbers with regex and validate in code 2.使用正则表达式捕获数字并在代码中验证

If you capture anything that looks like a number , you will be able to validate each parameter individually with IF clauses . 如果捕获看起来像数字的任何内容,您将能够使用IF clauses单独验证每个参数。 This will allow you to provide better feedback to the user. 这将允许您向用户提供更好的反馈。

a) #hex: a)#hex:

^(#)((?:[A-Fa-f0-9]{3}){1,2})$

The hash is also captured for consistency with the following expression. 还捕获哈希以与以下表达式保持一致。 DEMO DEMO

b) rgb(), rgba(), hsl() and hsla(): b)rgb(),rgba(),hsl()和hsla():

^(rgb|hsl)(a?)[(]\s*([\d.]+\s*%?)\s*,\s*([\d.]+\s*%?)\s*,\s*([\d.]+\s*%?)\s*(?:,\s*([\d.]+)\s*)?[)]$

This will create captures for the function and each parameter. 这将为函数和每个参数创建捕获。 DEMO DEMO


3. Validate with one monster regex: 3.使用一个怪物正则表达式验证:

This option is not recommended, mainly because it's quite difficult to read, it won't guarantee to match all use cases, and it will give you a headache if you try to debug it. 建议不要使用此选项,主要是因为它很难阅读,不能保证匹配所有用例,如果您尝试调试它会让您头疼。 The following regex validates the number of parameters allowed and ranges. 以下正则表达式验证允许的参数数量和范围。

a) #hex: ^#(?:[A-Fa-f0-9]{3}){1,2}$ DEMO a)#hex: ^#(?:[A-Fa-f0-9]{3}){1,2}$ DEMO

b) rgb(): ^rgb[(](?:\\s*0*(?:\\d\\d?(?:\\.\\d+)?(?:\\s*%)?|\\.\\d+\\s*%|100(?:\\.0*)?\\s*%|(?:1\\d\\d|2[0-4]\\d|25[0-5])(?:\\.\\d+)?)\\s*(?:,(?![)])|(?=[)]))){3}[)]$ DEMO b)rgb(): ^rgb[(](?:\\s*0*(?:\\d\\d?(?:\\.\\d+)?(?:\\s*%)?|\\.\\d+\\s*%|100(?:\\.0*)?\\s*%|(?:1\\d\\d|2[0-4]\\d|25[0-5])(?:\\.\\d+)?)\\s*(?:,(?![)])|(?=[)]))){3}[)]$ DEMO

c) rgba(): ^^rgba[(](?:\\s*0*(?:\\d\\d?(?:\\.\\d+)?(?:\\s*%)?|\\.\\d+\\s*%|100(?:\\.0*)?\\s*%|(?:1\\d\\d|2[0-4]\\d|25[0-5])(?:\\.\\d+)?)\\s*,){3}\\s*0*(?:\\.\\d+|1(?:\\.0*)?)\\s*[)]$ DEMO c)rgba(): ^^rgba[(](?:\\s*0*(?:\\d\\d?(?:\\.\\d+)?(?:\\s*%)?|\\.\\d+\\s*%|100(?:\\.0*)?\\s*%|(?:1\\d\\d|2[0-4]\\d|25[0-5])(?:\\.\\d+)?)\\s*,){3}\\s*0*(?:\\.\\d+|1(?:\\.0*)?)\\s*[)]$ DEMO

d) hsl(): ^hsl[(]\\s*0*(?:[12]?\\d{1,2}|3(?:[0-5]\\d|60))\\s*(?:\\s*,\\s*0*(?:\\d\\d?(?:\\.\\d+)?\\s*%|\\.\\d+\\s*%|100(?:\\.0*)?\\s*%)){2}\\s*[)]$ DEMO d)hsl(): ^hsl[(]\\s*0*(?:[12]?\\d{1,2}|3(?:[0-5]\\d|60))\\s*(?:\\s*,\\s*0*(?:\\d\\d?(?:\\.\\d+)?\\s*%|\\.\\d+\\s*%|100(?:\\.0*)?\\s*%)){2}\\s*[)]$ DEMO

e) hsla(): ^hsla[(]\\s*0*(?:[12]?\\d{1,2}|3(?:[0-5]\\d|60))\\s*(?:\\s*,\\s*0*(?:\\d\\d?(?:\\.\\d+)?\\s*%|\\.\\d+\\s*%|100(?:\\.0*)?\\s*%)){2}\\s*,\\s*0*(?:\\.\\d+|1(?:\\.0*)?)\\s*[)]$ DEMO e)hsla(): ^hsla[(]\\s*0*(?:[12]?\\d{1,2}|3(?:[0-5]\\d|60))\\s*(?:\\s*,\\s*0*(?:\\d\\d?(?:\\.\\d+)?\\s*%|\\.\\d+\\s*%|100(?:\\.0*)?\\s*%)){2}\\s*,\\s*0*(?:\\.\\d+|1(?:\\.0*)?)\\s*[)]$ DEMO

All toghether now: 现在全都是这样的:

With the above expressions, we can create this one-liner to validate all legal color values: 通过上面的表达式,我们可以创建这个单行来验证所有合法的颜色值:

^(?:#(?:[A-Fa-f0-9]{3}){1,2}|(?:rgb[(](?:\s*0*(?:\d\d?(?:\.\d+)?(?:\s*%)?|\.\d+\s*%|100(?:\.0*)?\s*%|(?:1\d\d|2[0-4]\d|25[0-5])(?:\.\d+)?)\s*(?:,(?![)])|(?=[)]))){3}|hsl[(]\s*0*(?:[12]?\d{1,2}|3(?:[0-5]\d|60))\s*(?:\s*,\s*0*(?:\d\d?(?:\.\d+)?\s*%|\.\d+\s*%|100(?:\.0*)?\s*%)){2}\s*|(?:rgba[(](?:\s*0*(?:\d\d?(?:\.\d+)?(?:\s*%)?|\.\d+\s*%|100(?:\.0*)?\s*%|(?:1\d\d|2[0-4]\d|25[0-5])(?:\.\d+)?)\s*,){3}|hsla[(]\s*0*(?:[12]?\d{1,2}|3(?:[0-5]\d|60))\s*(?:\s*,\s*0*(?:\d\d?(?:\.\d+)?\s*%|\.\d+\s*%|100(?:\.0*)?\s*%)){2}\s*,)\s*0*(?:\.\d+|1(?:\.0*)?)\s*)[)])$

DEMO DEMO

Or the regex enthusiasts can check this huge regex , with 148 color names. 或者正则表达式爱好者可以检查这个巨大的正则表达式 ,有148个颜色名称。 But I would never recommend using that pattern. 但我绝不会建议使用那种模式。 Please use the first option, creating a dummy element, which is the only way to cover all use cases for the browser. 请使用第一个选项,创建一个虚拟元素,这是覆盖浏览器所有用例的唯一方法。

I dont know about other browsers but in chrome the color will only be set if its valid: 我不知道其他浏览器,但在chrome中,只有在其有效时才会设置颜色:

var isValidColor = function(color) {
  var el = document.createElement('div');
  el.style.backgroundColor = color;
  return el.style.backgroundColor ? true : false;
};

console.log(isValidColor('#ff0000')); // true
console.log(isValidColor('rgb(0, 0)')); // false

It will have it's pitfalls though, because Chrome will do auto rounding of numbers: 但它会有陷阱,因为Chrome会自动舍入数字:

// 0, 0, 256 is not a valid color, but this says yes
console.log(isValidColor('rgb(0, 0, 256)')); // true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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