最近剛好碰到Html5的<input type="color"/>
當我選擇好顏色的時候,取到的值會是#ff0000,但有時開發人員會想取得RGB的值也就是RGB(255,255,255),您可以參考這篇資料 Convert rgb color to hex color
程式碼如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Pragma" content="No-cache" />
<title>顏色16進位轉RGB 或 RGB轉16進位</title>
<script src="js/jquery-2.0.2.min.js"></script>
<script type="text/javascript">
//RGB轉16進位
function rgb2hex(rgb){
var hexDigits = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
var hex = function(x){
return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
};
var tmp = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
var color = hex(tmp[1]) + hex(tmp[2]) + hex(tmp[3]);
return color;
}
//16進位轉RGB
function hex2rgb(v){
if (/^[0-9A-F]{3}$|^[0-9A-F]{6}$/.test(v.toUpperCase())) {
if (v.length == 3) {
v = v.match(/[0-9A-F]/g);
v = v[0] + v[0] + v[1] + v[1] + v[2] + v[2];
this.value = v;
}
var r = parseInt(v.substr(0, 2), 16);
var g = parseInt(v.substr(2, 2), 16);
var b = parseInt(v.substr(4, 2), 16);
return [r, g, b].join(',');
}
return v;
}
var hex,rgb;
//背景色
$('#BColor').change(function(){
hex=$('#BColor').val().replace('#', ''); //將#字號取代掉
rgb ='rgb('+hex2rgb(hex)+')';
alert(rgb);
});
</script>
</head>
<body>
Bg:<input type="color" id="BColor"/>
</body>
</html>
沒有留言:
張貼留言