.bgColor0{background-color:#158AEA}
.bgColor1{background-color:#996633}
.bgColor2{background-color:#66FF00}
获取012三个随机数前面添加字符串'bgColor'就得到随机的类名,然后给相应的元素添加得到的随机类名就行了。
而要获取012三个随机数就用Math.floor(Math.random()*3)获取。
不过你要求背景色不能重复,那么就把三个类名放进一个数组里。已经使用的类名就用”数组名.shift“把它从数组中弹出。然后剩下的两个类名就要获取01两个随机数,就用Math.floor(Math.random()*2)获取0和1其中一个数。
剩下的你知道该怎么做了。
function bg(){var r=Math.floor(Math.random()*256)
var g=Math.floor(Math.random()*256)
var b=Math.floor(Math.random()*256)
return "rgb("+r+','+g+','+b+")"
}