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、基于时间,亦可以产生随机数

 var now=new Date();
var number = now.getSeconds(); //这将产生一个基于目前时间的0到59的整数。 var now=new Date();
var number = now.getSeconds()%43; //这将产生一个基于目前时间的0到42的整数。

参考来源:http://www.studyofnet.com/news/181.html

例子:js获取随机颜色

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style type="text/css">
#box{width: 100px;height: 100px;margin: 20px auto;background-color: #c66;}
</style>
<body>
<div id="box" onclick="getColor();">box1</div>
<script type="text/javascript">
var x,y,z;
var oBox=document.getElementById('box');
function getColor(box){
x=Math.round(Math.random()*255);
y=Math.round(Math.random()*255);
z=Math.round(Math.random()*255);
oBox.style.backgroundColor='rgb('+x+','+y+','+z+')';
}
</script>
</body>
</html>

坚持下去,相信自己。

最新文章

  1. 我的LESS编译方案
  2. VScode调试Python
  3. 【COGS】894. 追查坏牛奶
  4. MVC数据验证
  5. c语言知识(2)
  6. 开源字体包缩减font-spider
  7. 转载:linux capability深入分析
  8. JQUERY1.9学习笔记 之基本过滤器(九) 小于选择器
  9. Chrome extension
  10. pod setup 报CocoaPods was not able to update the `master` repo 错误解决办法
  11. jQuery2.x源码解析(DOM操作篇)
  12. [js高手之路]html5 canvas动画教程 - 自己动手做一个类似windows的画图软件
  13. NVL2 这个函数,
  14. [ZJOI2007]报表统计
  15. 安装ubuntu系统及ubuntu安装Python的几点心得
  16. [日志分析] Access Log 日志分析
  17. Android破解学习之路(十五)—— 【Unity3D】洛菲斯的呼唤(Lophis roguelike)无限金币(道具)的实现 破解
  18. JS 自由变量---JS 学习笔记(三) 补充
  19. bug狩猎
  20. python 内置函数(一),低阶内置函数功能汇总

热门文章

  1. 【Unity3D游戏开发】性能优化之缩减打包压缩包大小 (二八)
  2. js 返回并刷新
  3. WebRTC的学习(一)
  4. Task&lt;TResult&gt;的使用
  5. celery入门
  6. SQL 2008下载地址以及全新安装详细过程
  7. [SAP ABAP开发技术总结]动态修改选择屏幕
  8. 查看perl及其模块
  9. 用Java集合中的Collections.sort方法对list排序的两种方法
  10. Android 设置进度条背景