JS隨機顏色有很多地方要用到:比如大家看到很多標簽連接都是五顏六色。實現隨機顏色的方法有多種,下面來看看具體的實現代碼:
方法一:
var getRandomColor = function() { return '#' + (function(color) { return (color += '0123456789abcdef' [Math.floor(Math.random() * 16)]) && (color.length == 6) ? color : arguments.callee(color); })(''); }
隨機生成6個字符然后再串到一起,閉包調用自身與三元運算符讓程序變得內斂;其實分解開來,代碼相當於:
function _g(color) { if ((color += '0123456789abcdef' [Math.floor(Math.random() * 16)]) && (color.length == 6)) { return color } else { return arguments.callee(color); } } var getRandomColor = function() { return '#' + _g(''); }
首先從getRandomColor函數里面傳過來一個空字符串,首先連接上'0123456789abcdef'字符串里面隨機的一個字母,也就是這段代碼:color += '0123456789abcdef'[Math.floor(Math.random()*16)];
然后判斷color這個變量的長度是不是為6,因為標准的顏色值是一個長度為6的字符串,第一次執行為1,所以不滿足,執行問號后面的arguments.callee(color);自調用;
方法二:
var getRandomColor = function() { return (function(m, s, c) { return (c ? arguments.callee(m, s, c - 1) : '#') + s[m.floor(m.random() * 16)] })(Math, '0123456789abcdef', 5) }
把Math對象,用於生成hex顏色值的字符串提取出來,並利用第三個參數來判斷是否還繼續調用自身。
方法三:
//隨機顏色,十六進制方法; function getRandomColor( ) { var rand = Math.floor(Math.random( ) * 0xFFFFFF).toString(16); if(rand.length == 6){ return rand; }else{ return getRandomColor(); } }
這個方法用到了十六進制與十進制的轉換,我們熟知的顏色值比如#ffffff這種寫法是十六進制顏色寫法,將其轉換為十進制之后得到16777215;轉換代碼如下:
var a="#ffffff" console.log(parseInt(a.slice(1),16)) // ==> 16777215
然后我們再將16777215轉換為十六進制,可以得到ffffff,前面的#號在十六進制中就是0x,所以就有了上面代碼中的0xFFFFFF了;
var a=16777215 console.log(a.toString(16)) // ==> ffffff
方法四:HSL模式顏色隨機;
var getRandomColor = function() { return "hsl(" + Math.round(Math.random() * 360) + "," + Math.round(Math.random() * 100) + '%,' + Math.round(Math.random() * 100) + '%)'; }
方法五:RGB模式隨機;
var getRandomColor = function() { return "rgb(" + Math.round(Math.random() * 255) + "," + Math.round(Math.random() * 255) + ',' + Math.round(Math.random() * 10) + ')'; }
方法六:RGB模式隨機另外一種方法;
var getRandomColor = function () { var r = Math.round(Math.random() * 255), g = Math.round(Math.random() * 255), b = Math.round(Math.random() * 255); var color = r << 16 | g << 8 | b; return "#" + color.toString(16) }
