下面提供了三種獲取隨機顏色值的方法數組
方法一:dom
建立一個顏色 HEX 值數組,而後隨機抽取這個數組裏6個值,組合生成顏色。spa
function color1(){ var color = ""; var colors = [0,1,2,3,4,5,6,7,8,9,"a","b","c","d","e","f"]; for(var i=0;i<6;i++){ var n = Math.ceil(Math.random()*15); color += "" + colors[n]; if(i==5){ return "#"+color; } } }
簡寫:code
function color4(){ return '#' + (function(color){ return (color += '0123456789abcdef'[Math.floor(Math.random()*16)]) && (color.length == 6) ? color : arguments.callee(color); })(''); }
方法二:blog
在0-16777215之間的生成一個隨機數,而後轉換爲16進制,若是沒有6位數就在前面加 0。字符串
function color2(){ var color = Math.ceil(Math.random()*16777215).toString(16); while(color.length<6){ color = "0" + color; } return "#"+color; }
方法三:io
這個和上面那個方法差很少,隨機數轉成16進制,和前面5個0的字符生成一個長字符串,再截取字符串最後6位字符。function
function color3(){ return '#'+('00000'+(Math.random()*0x1000000<<0).toString(16)).substr(-6); }