上代码栗子
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script>
<title>无标题文档</title>
<style>
#box{
width: 500px;
height:500px;
overflow: hidden;
border: 1px solid #ddd
}
img{max-width: 100%;}
</style>
</head>
<script language="JavaScript">
function rand(number) {
return Math.floor(Math.random()*number);
};
$(function(){
var arr = ['red','blue','yellow','green','black','pink','orange'];
var arrLength = arr.length;
$('#box').css('backgroundColor',arr[rand(arrLength)]); //取值0~6
})
</script>
<body>
<div id="box"></div>
</body>
</html>
取整函数
function rand(number) {
return Math.floor(Math.random()*number);
};
- 数组索引是从0开始的
- 如果是Math.round() 你会得到1-7 , 而不是0-6
- div颜色可能会得到undefined
- 用floor,可以得到0-6