简体   繁体   English

如何从rgb颜色的字符串中获取颜色值?

[英]How I can get the color value from string with rgb color?

I have an element with some background-color . 我有一个background-color的元素。 When I use element.style.backgroundColor then I get the string like rgb(221, 110, 43) . 当我使用element.style.backgroundColor然后我得到像rgb(221, 110, 43)的字符串。 How I can get, for example, blue value of the color (ie 43)? 例如,我如何获得颜色的蓝色值(即43)?

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], alpha: match[4] } : {}; } console.log(getRGB("rgb(211, 211, 211)").blue); console.log(getRGB("rgba(211, 0, 211, 0.5)")); 

You can use this regex to parse the RGB Color values. 您可以使用此正则表达式来解析RGB颜色值。

 var color = 'rgb(24, 45, 12)'; var parsedColor = color.match(/^rgb\\s*\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)$/i); console.log([parsedColor[1],parsedColor[2],parsedColor[3]]); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM