单独的红绿蓝值rgba颜色值

时间:2014-03-13 05:00:53

标签: javascript jquery

I' hv rgba这种格式的值RGBA(205,31,31,1)我希望将每个红色,绿色,蓝色和alpha值分开,以便进一步处理如何使用jQuery实现它; 所以输出看起来像

red = 205
green = 31
blue = 31
alpha =1

4 个答案:

答案 0 :(得分:2)

通过以下答案可以轻松地从字符串变量中获取这些值,因此您不需要jQuery

regex的帮助下,您可以轻松实现

var color = "RGBA(205,31,31,1)";
var regExp = /\(([^)]+)\)/;  // get the values within ()
var matches = regExp.exec(color);
var splits = matches[1].split(',');
alert("red: " + splits[0] + "green: " + splits[1]+ "blue: "+ splits[2]+ "alpha: " +splits[3] );

JSFiddle

但是要从元素获取rgba,您可以使用jQuery的css方法。

答案 1 :(得分:0)

var string = "RGBA(205,31,31,1)";

var colors = [];

string = string.replace(/[rgba\(\)]/gi, '');  // remove unnecessary characters

string = string.split(",");   // split by comma

for(var i = 0;i < string.length; i++){  
    colors.push(parseFloat(string[i], 10));  // parse the integer and push in colors array
}


console.log(colors); // [ 205, 31, 31, 1 ] the values are in RGBA order

答案 2 :(得分:0)

没有正则表达式:

var colorString = "rgba(111,222,333,0.5)",
    colorsOnly = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,\s*/),
    red = colorsOnly[0],
    green = colorsOnly[1],
    blue = colorsOnly[2],
    opacity = colorsOnly[3];

答案 3 :(得分:-1)

一种简单的现代方法:

"RGBA(205,31,31,1)".match(/[\d\.]+/g).map(Number); //==[205, 31, 31, 1]

或者如果你想要一个对象,那就更多了:

"RGBA(205,31,31,1)".match(/[\d\.]+/g).map(Number)
  .reduce(function(a,b,i){  
       a[["red","blue","green","alpha"][i]]=b; 
     return a;  
  }, {}); // ==  {red: 205, blue: 31, green: 31, alpha: 1}

使用“”.match()很好,因为它会忽略数字之间的空格以及“rgba”文本的大小写。