在点击时生成一个随机的颜色
随机生成十六进制颜色
var a,b = [],c="#" ;
document.querySelector('button').onclick = function(){
for(var i=0;i<6;i++){
a = Math.ceil( Math.random()*16).toString(16).toLocaleUpperCase();
b[i] = a;
c += b[i];
}
c = c.substr(0,7)
document.querySelector('div').style.backgroundColor = c;
console.log(c);
a = null;
b= [];
c= '#';
}
随机生成rgb颜色
function color(){
var rgb='rgb('+Math.floor(Math.random()*255)+','
+Math.floor(Math.random()*255)+','
+Math.floor(Math.random()*255)+')';
console.log(rgb);
return rgb;
}
document.querySelector('button').onclick = function(){
document.querySelector('div').style.backgroundColor = color();
}
第一种用到了字符串的一些方法,第二种方式使用原始的字符串拼接,很直观,第三种方式使用正则也可以实现,稍微要麻烦一些,没什么用,就不去写了。