如图所示:
将RGB格式的颜色值转换为十六进制格式的代码如下:
<script language="javascript">
function deal(){
form1.lastStr.value=convert(form1.str1.value,form1.str2.value,form1.str3.value);
}
</script>
<script language="javascript">
function formatNO(str,len){ //将数字字符串格式化为指定长度
var strLen=str.length;
for(i=0;i<len-strLen;i++){
str="0"+str;
}
return str;
}
</script>
<script language="javascript">
function convert(r,g,b){
if(isNaN(r)|| 255-r<0 ){
r=0;
}
if(isNaN(g)|| 255-g<0 ){
g=0;
}
if(isNaN(b)|| 255-b<0 ){
b=0;
}
var hr=formatNO(parseInt(r).toString(16),2);
var hg=formatNO(parseInt(g).toString(16),2);
var hb=formatNO(parseInt(b).toString(16),2);
var result="#"+hr+hg+hb;
return result;
}
</script>
<script language="javascript">
function check(obj){
var Expression=/^[0-9]+(\d*$)/;
var objExp=new RegExp(Expression);
if(objExp.test(obj.value)==false || 255-obj.value<0 ){
alert('要求输入0-255之间的整数!');
obj.focus();
}
}
</script>
<body>
<form action="" name="form1" method="post">
<table width="461" height="216" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="513" background="images/bg.gif"><table width="340" height="182" border="0" align="right" cellpadding="0" cellspacing="0">
<tr>
<td height="29"> </td>
<td >请输入要转换的RGB颜色值:</td>
</tr>
<tr>
<td> </td>
<td valign="middle">R:
<input name="str1" type="text" value="0" size="4" maxlength="3" onBlur="check(this)">
G:
<input name="str2" type="text" value="0" size="4" maxlength="3" onBlur="check(this)">
B:
<input name="str3" type="text" value="0" size="4" maxlength="3" onBlur="check(this)"></td>
</tr>
<tr>
<td> </td>
<td >格式化后的十六进制的颜色值:<br>
<br>
<input name="lastStr" type="text" readonly="yes" value=""></td>
</tr>
<tr>
<td width="50"> </td>
<td width="319"><input name="Submit" type="button" class="btn_grey" onClick="deal();" value="转换">
<input name="Submit2" type="button" class="btn_grey" onClick="window.location.reload()" value="刷新"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table></td>
</tr>
</table>
</form>
</body>