Convert RGB color value to RGBA at 0.75 alpha

让人想犯罪 __ 提交于 2019-12-23 07:00:09

问题


I have the following code to get the background color of an element.

var currentColor = $(this).css('background-color');

which returns something like rgb(123,123,123)

What I now want to do convert this to rgba and show it at 0.75 alpha

So returning something like rgba(123,123,123,0.75)

Any ideas?


回答1:


Since jQuery always seems to return the color like rgb(r, g, b) for elements that have no alpha, you could simply use:

$(this).css('background-color').replace(')', ', 0.75)').replace('rgb', 'rgba');

Just make sure the background color isn't rgba already:

var bg = $(this).css('background-color');
if(bg.indexOf('a') == -1){
    var result = bg.replace(')', ', 0.75)').replace('rgb', 'rgba');
}



回答2:


http://regex101.com/r/lT9iM4

var re = /(rgb)\(([0-9]+),\s+([0-9]+),\s+([0-9]+)/; 
var currentColor = $(this).css('background-color');
var subst = 'rgba($2,$3,$4,0.75'; 

$(this).css('background-color', currentColor.replace(re, subst));

Another solution using regex. But as Cerbrus mentioned, using regex for something this simple is overkill.




回答3:


Another regex try http://jsfiddle.net/hc3BA/

var colour = 'rgb(123,123,123)',
new_col = colour.replace(/rgb/i, "rgba");
new_col = new_col.replace(/\)/i,',0.75)');


来源:https://stackoverflow.com/questions/23608856/convert-rgb-color-value-to-rgba-at-0-75-alpha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!