常用的一些方法
<script>
var pai = Math.PI;
//圆周率
var ceil = Math.ceil(9.2);
//向上取整
var floor = Math.floor(9.8);
//向下取整
var min = Math.min(1,3,5,3,1);
//取最小值
var max = Math.max(1,2,3);
//取最大值
//在数组中应用
var arr = [1,2,3,1,2,3];
var arrMax = Math.max.apply(null,arr);
//不改变this指向,后面传数组
//null代表不改变this的指向
script>
<script>
function fun (min,max){
return Math.random()*(max-min)+min;
}
script>
<script>
function CoverInt(min,max){
return Math.round(Math.random()*(max-min)+min);
}
//另一种方法以后经常会用到
function CoverAll(min,max){
return Math.floor(Math.random()*(max+1-min)+min);
}
script>
<script>
function getColor(){
var r = Math.floor(Math.random()*256);
//256的原因:(max-min+1)+min
var g = Math.floor(Math.random()*256);
var b = Math.floor(Math.random()*256);
var a = Math.random();
//但是有个bug取不到1
var rgbas = "rgba"+"("+r+","+g+","+b+")";
return rgbas;
}
var box1 = document.querySelectorAll(".box1");
for(var i =0;i<box1.length;i++){
box1[i].style.backgroundColor = getColor();
}
//同学版
function f1(min,max){
return Math.round(Math.random()*(max-min)+min);
}
var lis = document.querySelectorAll("li");
for(var i = 0;i<lis.length;i++){
var r = f1(0,255);
var g = f1(0,255);
var b = f1(0,255);
lis[i].style.backgroundColor = "rgb("+r+","+g+","+b+")";
}
//老师版
//随机获取颜色转成16进制
//function同上,return "#"+r.toString(16)+g.toString(16)+a.toString(16);
//添加定时器,随机获取标签
function fun(){
setInterval(function(){
var li = document.createElement("li");
li.style.backgroundColor = getColor();
document.querySelector(".box").appendChild(li);
},1000)
fun();
}
script>