[英]Parse CSS Color to RGBA values
我想从某些<color> CSS数据类型值中获取RGBA值。
该函数应接受描述某种颜色的字符串,并返回具有红色,绿色,蓝色和alpha值的对象。
例如:
parseColor('red') -> { red: 255, green: 0, blue: 0, alpha: 1 }
parseColor('#f00') -> { red: 255, green: 0, blue: 0, alpha: 1 }
parseColor('rgb(255,0,0)') -> { red: 255, green: 0, blue: 0, alpha: 1 }
parseColor('hsla(0,100%,50%,0.1)') -> { red: 255, green: 0, blue: 0, alpha: 0.1 }
parseColor('transparent') -> { red: any_is_ok, green: any_is_ok, blue: any_is_ok, alpha: 0 }
因此,我尝试了如下代码:
function parseColor(color) {
var x = document.createElement('div');
document.body.appendChild(x);
var color, rgba;
var red = 0, green = 0, blue = 0, alpha = 0;
try {
x.style = 'color: ' + color + '!important';
color = window.getComputedStyle(x).color
rgba = color.match(/rgba?\((.*)\)/)[1].split(',').map(Number);
red = rgba[0];
green = rgba[1];
blue = rgba[2];
alpha = '3' in rgba ? rgba[3] : 1;
} catch (e) {
}
x.parentNode.removeChild(x);
return {'red': red, 'green': green, 'blue': blue, 'alpha': alpha};
}
它在Firefox,IE和Chrome中均可使用。 但是我不知道会返回什么window.getComputedStyle(x).color
? 此函数是否总是以rgb()
或rgba()
格式返回颜色? 规格说明了什么?
而且,还有其他方法可以实现parseColor
函数吗?
parseColor
函数通过创建虚拟元素并为其设置颜色来工作,因此它可以在rgba()或rgb()中获得颜色(取决于color
参数),但结果始终在rgba()中,因为
alpha = '3' in rgba ? rgba[3] : 1;
这意味着如果没有alpha(a),它将设置为1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.