package com.gary.util; import java.util.Random; /** * 颜色工具 * @author gary * */ public class ColorUtil { /** * 生成随机颜色代码 * @return */ public static String getRandomColorCode(){ //颜色代码位数 int colorLength = 6; //颜色代码数组 char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; StringBuffer sb = new StringBuffer("#"); Random random = new Random(); for (int i = 0; i < colorLength; i++) { sb.append(codeSequence[random.nextInt(16)]); } return sb.toString(); } public static void main(String[] args) { System.out.println(getRandomColorCode()); } }
JavaScript方式
function writeRandomColor(){ var rand = Math.round(Math.random() * 0x1000000); var color = "00000".concat(rand.toString(16)); document.write("#" + color.substr(color.length - 6, 6)); }