js 獲取隨機數方法如下:
1.Math.random()表示 結果為0-1間的一個隨機數(包括0,不包括1) ;
返回指定范圍的隨機數(m-n之間)的公式
Math.random()*(n-m)+m;
Math.random()*10+5; //返回5-15之間的隨機數
2.Math.ceil(n) 返回大于等于n的整數
用Math.ceil(Math.random()*10);時,主要獲取1到10的隨機整數,取0的幾率極小。
3、Math.round(n); 返回n四舍五入后整數的值。
用Math.round(Math.random());可均衡獲取0到1的隨機整數。
用Math.round(Math.random()*10);時,可基本均衡獲取0到10的隨機整數,其中獲取最小值0和最大值10
的幾率少一半。
4、Math.floor(n); 返回小于等于n的最大整數。
用Math.floor(Math.random()*10);時,可均衡獲取0到9的隨機整數。
5、基于時間,亦可以產生隨機數
1 var now=new Date(); 2 var number = now.getSeconds(); //這將產生一個基于目前時間的0到59的整數。 3
4 var now=new Date(); 5 var number = now.getSeconds()%43; //這將產生一個基于目前時間的0到42的整數。
參考來源:http://www.studyofnet.com/news/181.html
例子:js獲取隨機顏色
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Document</title>
6 </head>
7 <style type="text/css">
8 #box{width: 100px;height: 100px;margin: 20px auto;background-color: #c66;}
9 </style>
10 <body>
11 <div id="box" onclick="getColor();">box1</div>
12 <script type="text/javascript">
13 var x,y,z; 14 var oBox=document.getElementById('box'); 15
function getColor(box){ 16 x=Math.round(Math.random()*255); 17
y=Math.round(Math.random()*255); 18 z=Math.round(Math.random()*255); 19
oBox.style.backgroundColor='rgb('+x+','+y+','+z+')'; 20 } 21 </script>
22 </body>
23 </html>
堅持下去,相信自己。
|