bgcolor RGB 和16进制之间的转换,16进制转RGB,源码

时间:2024-09-01 00:03:20
<p>bgcolor RGB 和16进制之间的转换,16进制转RGB,源码例如:<br />
输入 201,255,201 转换成 #C9FFC9</p>
<p>
输入 #C9FFC9 转换成 201,255,201
</p>
<script type="text/javascript">// <![CDATA[
function RGBtoHex() {
R=document.form.R.value;
G=document.form.G.value;
B=document.form.B.value;
return document.form.res.value='#'+(toHex(R)+toHex(G)+toHex(B));
}
function toHex(N)
{
if (N==null) return "00";
N=parseInt(N);
if (N==0 || isNaN(N)) return "00";
N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
return "0123456789ABCDEF".charAt((N-N%16)/16)+ "0123456789ABCDEF".charAt(N%16);
}
// ]]></script>
<p>&nbsp;</p>
<form action="" name="form"> <strong>R<input type="text" name="R" size="3" maxlength="3" /> G<input type="text" name="G" size="3" maxlength="3" /> B<input type="text" name="B" size="3" maxlength="3" /> <input onclick="RGBtoHex();" type="button" value="转换" /> <input type="text" name="res" size="25" /><br />
</strong>
</form>
<p>&nbsp;</p>
<p>
<strong><br />
</strong></p>
<p>
<br />
</p>
<p>
<br />
</p>
<script type="text/javascript">// <![CDATA[
function HextoRGB() {
var v = document.form1.res.value;
if(v[0] != '#') v='#'+v;
document.form1.R.value = toTen(v[1])*16+parseInt(toTen(v[2]));
document.form1.G.value = toTen(v[3])*16+parseInt(toTen(v[4]));
document.form1.B.value = toTen(v[5])*16+parseInt(toTen(v[6]));
}
function toTen(num)
{
var result=0;
switch (num){
case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":
result =num;
break;
case "A":case "a":
result = 10;
break;
case "B":case "b":
result = 11;
break;
case "C":case "c":
result = 12;
break;
case "D":case "d":
result = 13;
break;
case "E":case "e":
result = 14;
break;
case "F":case "f":
result = 15;
break;
default:
break;
}
return result;
}
// ]]></script>
<form action="" name="form1"><input type="text" name="res" size="25" maxlength="7" /> <input onclick="HextoRGB();" type="button" value="转换" /> R<input type="text" name="R" size="3" maxlength="3" /> G<input type="text" name="G" size="3" maxlength="3" /> B<input type="text" name="B" size="3" maxlength="3" /></form>