Math.random() 获取0到1的随机数[0,1)
获取0-100之间的随机数
console.log(Math.floor(Math.random()*101));
获取20-80的随机数
console.log(Math.floor(Math.random()*61)+20);
获取 x—y的随机数
Math.floor(Math.random()*(y-x+1))+x
例子:随机改变div的颜色
.wp {
height: 200px;
width: 200px;
background: #f00;
}
<div class="wp" id="wp"></div>
<input type="button" id="btn" value="改变颜色" />
<script type="text/javascript">
var wp = document.getElementById("wp");
var btn = document.getElementById("btn");
btn.onclick = function(){
var r = Math.floor(Math.random()*256);
var g = Math.floor(Math.random()*256);
var b = Math.floor(Math.random()*256);
wp.style.background = 'rgb('+r+','+g+','+b+')';
};
</script>