首页 > 程序开发 > web前端 > JavaScript >

js 获取随机颜色值

2012-09-12

[javascript]/** 获取随机颜色值* @param min,最小取值,取值范围0-255* @param max,最大取值,取值范围0-255*/function getColor(min,max){ var co = ""; co+=(getRandom(min,max)+","); co+=(ge...

[javascript]
/*
* 获取随机颜色值
* @param min,最小取值,取值范围0-255
* @param max,最大取值,取值范围0-255
*/
function getColor(min,max){
var co = "";
co+=(getRandom(min,max)+",");
co+=(getRandom(min,max)+",");
co+=getRandom(min,max);
return RGB2Hex(co);
}

/*
* 获取指定范围随机数
* @param min,最小取值
* @param max,最大取值
*/

function getRandom(min,max){
//x上限,y下限
var x = max;
var y = min;
if(x<y){
x=min;
y=max;
}
var rand = parseInt(Math.random() * (x - y + 1) + y);
return rand;
}

/*
* 获取颜色值
* @param rgb, RGB颜色值,如 "23,189,246"
*/
function RGB2Hex(rgb){
var re = rgb.replace(/(?:\(|\)|rgb|RGB)*/g,"").split(",");//利用正则表达式去掉多余的部分
var hexColor = "#";
var hex = [&#39;0&#39;, &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;, &#39;8&#39;, &#39;9&#39;, &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;];
for (var i = 0; i < 3; i++) {
var r = null;
var c = re[i];
var hexAr = [];
while (c > 16) {
r = c % 16;
c = (c / 16) >> 0;
hexAr.push(hex[r]);
}
hexAr.push(hex[c]);
hexColor += hexAr.reverse().join(&#39;&#39;);
}
return hexColor;

相关文章
最新文章
热点推荐