如何在javascript中从rgb字符串中提取颜色值

时间:2020-12-16 21:24:37

Javascript code

Javascript代码

$(".designer-element").each(function () {
        var $this = $(this),
        var  moot = $this.css(["color", "border-color", "background-color"]);
} );

is used to get element colors. This returns colors as strings like

用于获取元素颜色。它以字符串的形式返回颜色

"background-color": "rgba(0, 0, 0, 0)"
"border-color": "rgb(211, 211, 211)"
"color": "rgb(51, 51, 51)"

How to extract individual r , g and b values from those strings. a value is not needed. Or is there some better method which returns those color values directly?

如何从这些字符串中提取单个的r、g和b值。不需要值。或者有没有更好的方法直接返回这些颜色值?

substrg cannot used since values have variable sizes 1-3 digits Can some regex used ?

substrg不能使用,因为值有变量大小1-3位,regex可以使用吗?

html5, jquery, jquery-ui and bootstrap are used.

使用html5、jquery、jquery-ui和bootstrap。

4 个解决方案

#1


4  

You can use a regex:

您可以使用regex:

function getRGB(str){
  var match = str.match(/rgba?\((\d{1,3}), ?(\d{1,3}), ?(\d{1,3})\)?(?:, ?(\d(?:\.\d?))\))?/);
  return match ? {
    red: match[1],
    green: match[2],
    blue: match[3]
  } : {};
}

console.log(getRGB("rgb(211, 211, 211)"));
console.log(getRGB("rgba(211, 0, 211, 0.5)"));

#2


1  

If you want to avoid Regular Expression usage for performance reasons, try something like:

如果您希望避免由于性能原因而使用正则表达式,请尝试以下操作:

function getRGBValues(str) {
  var vals = str.substring(str.indexOf('(') +1, a.length -1).split(', ');
  return {
    'r': vals[0],
    'g': vals[1],
    'b': vals[2]
  };
}

```

' ' '

#3


0  

use regular expression to capture the rbg values something like below

使用正则表达式捕获如下所示的rbg值

~ /((.*?))/

~ / /((?))

then you will get "0,0,0" split that using string and you will get array of numbers and depending on the length of the array determine individual values

然后你会得到“0,0,0”用字符串分割,你会得到数组的数字,根据数组的长度决定单个的值。

#4


0  

This is what I use

这就是我用的

// return array of [r,g,b,a] from any valid color. if failed returns undefined
function colorValues(color)
{
    if (color === '')
        return;
    if (color.toLowerCase() === 'transparent')
        return [0, 0, 0, 0];
    if (color[0] === '#')
    {
        if (color.length < 7)
        {
            // convert #RGB and #RGBA to #RRGGBB and #RRGGBBAA
            color = '#' + color[1] + color[1] + color[2] + color[2] + color[3] + color[3] + (color.length > 4 ? color[4] + color[4] : '');
        }
        return [parseInt(color.substr(1, 2), 16),
            parseInt(color.substr(3, 2), 16),
            parseInt(color.substr(5, 2), 16),
            color.length > 7 ? parseInt(color.substr(7, 2), 16)/255 : 1];
    }
    if (color.indexOf('rgb') === -1)
    {
        // convert named colors
        var temp_elem = document.body.appendChild(document.createElement('fictum')); // intentionally use unknown tag to lower chances of css rule override with !important
        var flag = 'rgb(1, 2, 3)'; // this flag tested on chrome 59, ff 53, ie9, ie10, ie11, edge 14
        temp_elem.style.color = flag;
        if (temp_elem.style.color !== flag)
            return; // color set failed - some monstrous css rule is probably taking over the color of our object
        temp_elem.style.color = color;
        if (temp_elem.style.color === flag || temp_elem.style.color === '')
            return; // color parse failed
        color = getComputedStyle(temp_elem).color;
        document.body.removeChild(temp_elem);
    }
    if (color.indexOf('rgb') === 0)
    {
        if (color.indexOf('rgba') === -1)
            color += ',1'; // convert 'rgb(R,G,B)' to 'rgb(R,G,B)A' which looks awful but will pass the regxep below
        return color.match(/[\.\d]+/g).map(function (a)
        {
            return +a
        });
    }
}

https://gist.github.com/oriadam/396a4beaaad465ca921618f2f2444d49

https://gist.github.com/oriadam/396a4beaaad465ca921618f2f2444d49

Examples

例子

colorValues('transparent'); // [0,0,0,0]
colorValues('white'); // [255, 255, 255, 1]
colorValues('teal'); // [0, 128, 128, 1]
colorValues('rgba(11,22,33,.44)'); // [11, 22, 33, 0.44]
colorValues('rgb(11,22,33)'); // [11, 22, 33, 1]
colorValues('#abc'); // [170, 187, 204, 1]
colorValues('#abc6'); // [170, 187, 204, 0.4]
colorValues('#aabbcc'); // [170, 187, 204, 1]
colorValues('#aabbcc66'); // [170, 187, 204, 0.4]
colorValues('asdf'); // undefined
colorValues(''); // undefined
colorValues(NaN); // Script Error
colorValues(123); // Script Error

#1


4  

You can use a regex:

您可以使用regex:

function getRGB(str){
  var match = str.match(/rgba?\((\d{1,3}), ?(\d{1,3}), ?(\d{1,3})\)?(?:, ?(\d(?:\.\d?))\))?/);
  return match ? {
    red: match[1],
    green: match[2],
    blue: match[3]
  } : {};
}

console.log(getRGB("rgb(211, 211, 211)"));
console.log(getRGB("rgba(211, 0, 211, 0.5)"));

#2


1  

If you want to avoid Regular Expression usage for performance reasons, try something like:

如果您希望避免由于性能原因而使用正则表达式,请尝试以下操作:

function getRGBValues(str) {
  var vals = str.substring(str.indexOf('(') +1, a.length -1).split(', ');
  return {
    'r': vals[0],
    'g': vals[1],
    'b': vals[2]
  };
}

```

' ' '

#3


0  

use regular expression to capture the rbg values something like below

使用正则表达式捕获如下所示的rbg值

~ /((.*?))/

~ / /((?))

then you will get "0,0,0" split that using string and you will get array of numbers and depending on the length of the array determine individual values

然后你会得到“0,0,0”用字符串分割,你会得到数组的数字,根据数组的长度决定单个的值。

#4


0  

This is what I use

这就是我用的

// return array of [r,g,b,a] from any valid color. if failed returns undefined
function colorValues(color)
{
    if (color === '')
        return;
    if (color.toLowerCase() === 'transparent')
        return [0, 0, 0, 0];
    if (color[0] === '#')
    {
        if (color.length < 7)
        {
            // convert #RGB and #RGBA to #RRGGBB and #RRGGBBAA
            color = '#' + color[1] + color[1] + color[2] + color[2] + color[3] + color[3] + (color.length > 4 ? color[4] + color[4] : '');
        }
        return [parseInt(color.substr(1, 2), 16),
            parseInt(color.substr(3, 2), 16),
            parseInt(color.substr(5, 2), 16),
            color.length > 7 ? parseInt(color.substr(7, 2), 16)/255 : 1];
    }
    if (color.indexOf('rgb') === -1)
    {
        // convert named colors
        var temp_elem = document.body.appendChild(document.createElement('fictum')); // intentionally use unknown tag to lower chances of css rule override with !important
        var flag = 'rgb(1, 2, 3)'; // this flag tested on chrome 59, ff 53, ie9, ie10, ie11, edge 14
        temp_elem.style.color = flag;
        if (temp_elem.style.color !== flag)
            return; // color set failed - some monstrous css rule is probably taking over the color of our object
        temp_elem.style.color = color;
        if (temp_elem.style.color === flag || temp_elem.style.color === '')
            return; // color parse failed
        color = getComputedStyle(temp_elem).color;
        document.body.removeChild(temp_elem);
    }
    if (color.indexOf('rgb') === 0)
    {
        if (color.indexOf('rgba') === -1)
            color += ',1'; // convert 'rgb(R,G,B)' to 'rgb(R,G,B)A' which looks awful but will pass the regxep below
        return color.match(/[\.\d]+/g).map(function (a)
        {
            return +a
        });
    }
}

https://gist.github.com/oriadam/396a4beaaad465ca921618f2f2444d49

https://gist.github.com/oriadam/396a4beaaad465ca921618f2f2444d49

Examples

例子

colorValues('transparent'); // [0,0,0,0]
colorValues('white'); // [255, 255, 255, 1]
colorValues('teal'); // [0, 128, 128, 1]
colorValues('rgba(11,22,33,.44)'); // [11, 22, 33, 0.44]
colorValues('rgb(11,22,33)'); // [11, 22, 33, 1]
colorValues('#abc'); // [170, 187, 204, 1]
colorValues('#abc6'); // [170, 187, 204, 0.4]
colorValues('#aabbcc'); // [170, 187, 204, 1]
colorValues('#aabbcc66'); // [170, 187, 204, 0.4]
colorValues('asdf'); // undefined
colorValues(''); // undefined
colorValues(NaN); // Script Error
colorValues(123); // Script Error