简体   繁体   English

JavaScript从十六进制获取alpha值

[英]JavaScript to get alpha value from HEX

I am developing a tool which will convert html colors between maximum any format like RGB, RGBA, HEX, HSLA, NAMED etc. 我正在开发一个工具,可以将RGB颜色在RGB,RGBA,HEX,HSLA,NAMED等任何最大格式之间转换。

And also HEX(#FFFFFF) to Alpha HEX (#00FFFFFF) for use in filters in IE6. 还将HEX(#FFFFFF)转换为Alpha HEX(#00FFFFFF),以用于IE6中的过滤器。 But, my problem is that I am unable to convert the alpha value ie 00 from Alpha hex color to rgba alpha value ie 0.5. 但是,我的问题是我无法将alpha值(即00)从Alpha十六进制颜色转换为rgba alpha值(即0.5)。 please help me... 请帮我...

Just convert the first 2 digits from hex to number, then divide by 255. 只需将前两位数字从十六进制转换为数字,然后除以255。

var rx = /^#([0-9a-f]{2})[0-9a-f]{6}$/i;
var m = rx.match(theColor);
if (m) {
   alpha = parseInt(m[1], 16) / 255;
}

I know you already accepted KennyTM's answer, but I thought I'd add this anyway. 我知道您已经接受了KennyTM的回答,但我想还是要添加此内容。 You can use shifting and masking on a hex converted number to get certain parts of it: 您可以对十六进制转换后的数字使用移位和掩码来获取其中的某些部分:

// Return an array in the format [ red, green, blue, alpha ]
function hex2rgba(str) {
    var num = parseInt(str.slice(1), 16); // Convert to a number
    return [num >> 16 & 255, num >> 8 & 255, num & 255, num >> 24 & 255];
}

var rgba = hex2rgba("#00FFFFFF");
// -> [255, 255, 255, 0]

You can then divide the last element by 255 to get a value that can be used with IE filters. 然后,您可以将最后一个元素除以255,以获得可以与IE过滤器一起使用的值。

More information: 更多信息:

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

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