<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>无标题文档</title> <script language="javascript"> <!-- function showRGB(obj){ red=obj.red.value; green=obj.green.value blue=obj.blue.value; //将RGB转换为16进制Hex值 hexcode="#"+toHex(red)+toHex(green)+toHex(blue); document.bgColor=obj.hexval.value=hexcode; } function toHex(d){ if(isNaN(d)){ d=0; } //16进制转换方法 var n=new Number(d).toString(16); return (n.length==1?"0"+n:n); }//--> </script> </head> <body> <form name="rgbform"> <b>请输入RGB颜色值(0 to 255)</b><br> Red: <input type="text" name="red" size="5"><br> Green: <input type="text" name="green" size="5"><br> Blue: <input type="text" name="blue" size="5"><br> <input type="button" value="显示Hex #" onClick="showRGB(this.form)"> Hex值为: <input type="text" name="hexval" size="7"> </form> </body> </html>
本例的难点在于进制间的转换。代码中使用“toHex”方法实现10进制到16进制的转换,但主要靠“toString”方法实现,此方法带一个参数表示要转换的进制。