<!DOCTYPE html>
randomColor #square{ background-color: red; margin: auto; height: 200px; width: 200px; }
var colors = ['red','blue','yellow','green','black','purple']; function setColor(){ var n =0; var m = Math.floor(Math.random()*6); if (m == n){ setColor(); } else{ document.getElementById('square').style.backgroundColor = colors[m]; document.getElementById('para').innerHTML = colors[m]; } } function control(){ var button = document.getElementById("button"); if (button.value =="stop"){ clearInterval(change); button.value = "go on"; } else{ change = setInterval(setColor,500); button.value ="stop"; } }
var n =0; //写在外面
function setColor(){
var m = n;
while (m == n) m = Math.floor(Math.random()*6);
n = m;
document.getElementById('square').style.backgroundColor = colors[m];
document.getElementById('para').innerHTML = colors[m];
}
}
可以建立一个数组,表示每个颜色是否用过,取某一颜色的时候标志该数组的对应位置,取新颜色时查看是否已经标志过,标志过则重新选。
http://www.css88.com/tool/js_beautify/
js代码在线格式化
写个小的数组 先存储 生成下一个颜色时再判断