从color数组中随机取颜色值做为背景色? function cc(){ var color=["white","blue","green","orange","red"]; document.getElementById("a1").style.backgroundColor=color[Math.round(4*Math.random())]; document.getElementById("a2").style.backgroundColor=color[Math.round(4*Math.random())]; }
是,但两种颜色要不同。所以用了splice函数,但使用后ie6下就不运行了,不知何故。
.style.backgroundColor要求是字符串 但splice函数的返回值是个数组,不是字符串 function cc() { var color=new Array("white","blue","green","orange","red"); document.getElementById("a1").style.backgroundColor=color.splice(Math.floor(Math.random()*color.length),1)[0]; document.getElementById("a2").style.backgroundColor=color.splice(Math.floor(Math.random()*color.length),1)[0]; }
偷个懒,保证每次的两种不同,但不排除与上一批次的相同,需要的话,自己加上些逻辑去判断吧 function cc(){ var color=["pink","blue","green","orange","red"].sort(function(){return 0.5 - Math.random()}); color.length=2; document.getElementById("a1").style.backgroundColor=color[0]; document.getElementById("a2").style.backgroundColor=color[1]; }
function cc(){
var color=["white","blue","green","orange","red"];
document.getElementById("a1").style.backgroundColor=color[Math.round(4*Math.random())];
document.getElementById("a2").style.backgroundColor=color[Math.round(4*Math.random())];
}
是,但两种颜色要不同。所以用了splice函数,但使用后ie6下就不运行了,不知何故。
但splice函数的返回值是个数组,不是字符串
function cc()
{
var color=new Array("white","blue","green","orange","red");
document.getElementById("a1").style.backgroundColor=color.splice(Math.floor(Math.random()*color.length),1)[0];
document.getElementById("a2").style.backgroundColor=color.splice(Math.floor(Math.random()*color.length),1)[0];
}
function cc(){
var color=["pink","blue","green","orange","red"].sort(function(){return 0.5 - Math.random()});
color.length=2;
document.getElementById("a1").style.backgroundColor=color[0];
document.getElementById("a2").style.backgroundColor=color[1];
}