最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - JavaScript to get alpha value from HEX - Stack Overflow

programmeradmin5浏览0评论

I am developing a tool which will convert html colors between maximum any format like RGB, RGBA, HEX, HSLA, NAMED etc.

And also HEX(#FFFFFF) to Alpha HEX (#00FFFFFF) for use in filters in IE6. But, my problem is that I am unable to convert the alpha value i.e. 00 from Alpha hex color to rgba alpha value i.e. 0.5. please help me...

I am developing a tool which will convert html colors between maximum any format like RGB, RGBA, HEX, HSLA, NAMED etc.

And also HEX(#FFFFFF) to Alpha HEX (#00FFFFFF) for use in filters in IE6. But, my problem is that I am unable to convert the alpha value i.e. 00 from Alpha hex color to rgba alpha value i.e. 0.5. please help me...

Share asked Sep 4, 2010 at 10:21 Vaibhav GuptaVaibhav Gupta 1,6121 gold badge14 silver badges23 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Just convert the first 2 digits from hex to number, then divide by 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. 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.

More information:

  • http://en.wikipedia/wiki/Bitwise_operation
发布评论

评论列表(0)

  1. 暂无评论