RGBと16進数の変換
RGB形式と16進数形式の色の相互変換
jQuery
$(function () {
// 16進数
$('#hex').blur(function() {
var str = $(this).val();
$('#color').css('background', str);
if (str.length < 6) {
// #abcをa,b,cに分割
var hex_3digit = str.match(/^#([0-9a-f]{1})([0-9a-f]{1})([0-9a-f]{1})/);
// aa
var hex_r = hex_3digit[1] + hex_3digit[1];
// bb
var hex_g = hex_3digit[2] + hex_3digit[2];
// cc
var hex_b = hex_3digit[3] + hex_3digit[3];
} else {
// #abcdefをab,cd,efに分割
var hex_6digit = str.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/);
// ab
var hex_r = hex_6digit[1];
// cd
var hex_g = hex_6digit[2];
// ef
var hex_b = hex_6digit[3];
}
// 16進数から10進数へ
var rgb_r = parseInt(hex_r, 16);
var rgb_g = parseInt(hex_g, 16);
var rgb_b = parseInt(hex_b, 16);
$('#r').val(rgb_r);
$('#g').val(rgb_g);
$('#b').val(rgb_b);
});
// RGB
$('#r,#g,#b').blur(function() {
var rgb_r = $('#r').val();
var rgb_g = $('#g').val();
var rgb_b = $('#b').val();
// 10進数から16進数へ
var hex_r = (parseInt(rgb_r)).toString(16);
var hex_g = (parseInt(rgb_g)).toString(16);
var hex_b = (parseInt(rgb_b)).toString(16);
// 1桁の場合は0をつける
hex_r = hex_r.replace(/(^[0-9a-f]{1}$)/, '0$1');
hex_g = hex_g.replace(/(^[0-9a-f]{1}$)/, '0$1');
hex_b = hex_b.replace(/(^[0-9a-f]{1}$)/, '0$1');
var hex = '#' + hex_r + hex_g + hex_b;
$('#hex').val(hex);
$('#color').css('background', $('#hex').val());
});
});
CSS
article {
display: none;
}
article.selected {
display: block;
}
HTML
<form>
<span id="color" style="background: #1546c3"> </span>
<input type="text" id="hex" maxlength="7" size="8" value="#1546c3" pattern="^#([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$">
<span>―</span>
<label for="r">R</label>
<input type="text" id="r" maxlength="3" size="4" value="21" pattern="^(1?[0-9]?[0-9]|2[0-4]?[0-9]|25[0-5])$">
<label for="g">G</label>
<input type="text" id="g" maxlength="3" size="4" value="70" pattern="^(1?[0-9]?[0-9]|2[0-4]?[0-9]|25[0-5])$">
<label for="b">B</label>
<input type="text" id="b" maxlength="3" size="4" value="195" pattern="^(1?[0-9]?[0-9]|2[0-4]?[0-9]|25[0-5])$">
</form>
サンプル