Convert jQuery RGB output to Hex Color

http://wowmotty.blogspot.com/2009/06/convert-jquery-rgb-output-to-hex-color.html

My current project uses Farbtastic which is a fantastic jQuery plugin which allows users to visually choose a color for an element. The problem I ran into was loading a default color from the element:

jQuery returns the element color in RGB format

document.write( $('#myElement').css('background-color') );
// outputs: rgb(34, 34, 34)

but Farbtastic uses the hex color format, just like the CSS.
#myElement { background-color: #222222 }
I found this  really nice script  (by R0bb13) which converts RGB to hex. This script requires the input variable to be in an array "[34,34,34]". In order to make the script use an RGB format "rgb(34,34,34)", I had to add one line to the script to remove the "rgb" and parenthesis and then convert (split) the result into an array...

Update #2  (allows entering an rgba value - opacity is ignored)

allowfullscreen="allowfullscreen" frameborder="0" src="http://jsfiddle.net/Mottie/xcqpF/1/embedded/result,js,html" style="color: rgb(255, 255, 255); font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; line-height: 18.2000007629395px; height: 300px; width: 686px; background-color: rgb(20, 20, 20);"> Updated  (removing internal function):
//Function to convert hex format to a rgb color
function rgb2hex(rgb){
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 return "#" +
  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[3],10).toString(16)).slice(-2);
}
Here is an example of how to use this code with jQuery:
document.write( rgb2hex($('#myElement').css('background-color')) );
// outputs: #222222
Here is the original code from this post (not nearly as efficient as the updated script):
//Function to convert hex format to a rgb color
function rgb2hex(rgb) {
var hexDigits = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值