如何从JavaScript中的rgb字符串中提取颜色值 [英] How to extract color values from rgb string in javascript
本文介绍了如何从JavaScript中的rgb字符串中提取颜色值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
JavaScript代码
$(designer-element $ this = $(this),
var moot = $ this.css([color,border-color,background-color]);
});
用于获取元素颜色。这会返回颜色为字符串
background-color:rgba(0,0,0,0)
border-color:rgb(211,211,211)
color:rgb(51,51,51)
如何从这些字符串中提取单个r,g和b值。不需要值。
或者有更好的方法直接返回这些颜色值吗?
substrg不能使用,因为值有1-3个数字的可变大小
regex使用?
解决方案
html5,jquery,jquery-ui和bootstrap。 div>
您可以使用regex:
function getRGB(str){var match = str.match(/ rgba?\ ((\d {1,3}),?(\d {1,3}),?(\d {1,3})\)? :\.\d?))\))?/);返回匹配? {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)));
Javascript code
$(".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?
substrg cannot used since values have variable sizes 1-3 digits Can some regex used ?
html5, jquery, jquery-ui and bootstrap are used.
解决方案
You can use a 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)"));
这篇关于如何从JavaScript中的rgb字符串中提取颜色值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文