1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title></title>
6 <meta name="author" content="郭菊锋702004176@qq.com"/>
7 <style type="text/css">
8 div{
9 width: 100px;
10 height: 100px;
11 }
12 </style>
13 <script type="text/javascript">
14 window.onload = function(){
15 var oDiv1 = document.getElementById("div1");
16 var oDiv2 = document.getElementById("div2");
17 var a = Math.floor(Math.random()*225);
18 var b = "rgb("+Math.floor(Math.random()*225)+","+Math.floor(Math.random()*225)+","+Math.floor(Math.random()*225)+")";
19 var c = "rgb("+a+","+a+","+a+")";
20 oDiv1.style.backgroundColor = b;
21 oDiv2.style.backgroundColor = c;
22
23 console.log(a);
24 console.log(b+"rgb要想不一样,要三个公式分开分别穿进去,不能合起来。");
25 console.log(c+"用a替换公式的时候,传出来的rgb三个值都一样了,这样只能配到白到黑的灰度值。");
26 /*
27 *为了日后用起来方便,定义成一个函数的写法。
28 *
29 */
30 // function getRandomColor(){
31 // var rgb='rgb('+Math.floor(Math.random()*255)+','
32 // +Math.floor(Math.random()*255)+','
33 // +Math.floor(Math.random()*255)+')';
34 // console.log(rgb);
35 // return rgb;
36 // }
37 // oDiv.style.backgroundColor =getRandomColor();
38 }
39
40 </script>
41 </head>
42 <body>
43 <div id="div1"></div>
44 <div id="div2"></div>
45 </body>
46 </html>
47
以上,是第一种,用rgb(r,g,b)的方式传来的,
精髓是,r=0-255之间任意值。gb同理。利用Math.random()*255取得0-254之间的无限近似小数,再利用Math的floor取整,或者用parseInt取整,得到整数0-255。然后穿进去代替rgb的响应位置即可。
这里说:Math.random()*255,怎么得出0-224的近似小数:Math.random()本身得出的是0-1之间的任意小数值,包括0不包括1。
也就是说:Math.random()取出来的最小值是:0,最大值是0.9999999999999999999999999999,反正不会等于 1,就无限向后走,接下来,当取到0或者0.000000000000000000123等这些数时,再乘以255,结果还是0或者0.0000000多,经过我们一取整,得到的便是0了。而最大值乘以255时,得到的是254.12493....(无限),这样Math.floor()向上取整得到255.
以下,是常用的,#xxxxxx颜色值得设置方法:
#xxxxxx精髓:0123456789abdefx这几个值中,随意匹配6个即可。