自动生成十六进制颜色
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <style> * { margin: 0; padding: 0; } #box { width: 500px; height: 500px; margin: 0 auto; background: red; } </style> <body> <div id="box"></div> <script> function getColor() { var str = "#"; //创建一个函数。因为里面有number类型也有string类型的。所以统一用string类型 var arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; for(var i = 0; i < 6; i++) { var num = parseInt(Math.random() * 16); //创建一个从0-15的随机数 str += arr[num]; } return str; } document.getElementById('box').style.backgroundColor = getColor(); </script> </body> </html>
做一个随机函数
//随机生成一个0-many数字的数组(有重复) function randomNumber(many){ var arr=[]; for(var i=0;i<many;i++){ var result=parseInt(Math.random()*many); arr[arr.length]=result+1; }; return arr; }; //console.log(randomNumber(10));