javascript 将 RGB 颜色值转换为 0.75 alpha 的 RGBA

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23608856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:12:57  来源:igfitidea点击:

Convert RGB color value to RGBA at 0.75 alpha

javascriptjquerycssrgba

提问by Tom

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)

它返回类似的东西 rgb(123,123,123)

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

我现在想做的是将其转换为 rgba 并以 0.75 alpha 显示

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

所以返回类似的东西 rgba(123,123,123,0.75)

Any ideas?

有任何想法吗?

回答by Cerbrus

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

由于 jQuery 似乎总是rgb(r, g, b)为没有 alpha 的元素返回颜色,因此您可以简单地使用:

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

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

只需确保背景颜色不是 rgba:

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

回答by Henrik Peinar

http://regex101.com/r/lT9iM4

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(,,,0.75'; 

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

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

使用正则表达式的另一种解决方案。但正如Cerbrus 所提到的,将正则表达式用于如此简单的事情是过度的。

回答by nicolallias

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

另一个正则表达式尝试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)');