利用数组将九种颜色不重复的显示在九个盒子中
排除与选入
var ArrList=['#00b8e1','#e65e20','#64be10','#eb7327','#19a657','#e2a019','#8e28c5','#034f95','#92ce4b']; function getArrayItems(ColorArr, num) { var Color_array = new Array(); for(var index in ColorArr) { Color_array.push(ColorArr[index]); } var return_array = new Array(); for(var i = 0; i < num; i++) { if(Color_array.length > 0) { var arrIndex = Math.floor(Math.random() * Color_array.length); return_array[i] = Color_array[arrIndex]; Color_array.splice(arrIndex, 1); //把筛选出的给这个新的数组,然后删除前一个 } else { break; } } return return_array; }
调用选取的结果
function addHtmlxl(){ var newArray = getArrayItems(ArrList,10); $('.divColor').each( function(index, val) { $(val).css('backgroundColor',newArray[index]); }); } $(document).ready(function(){ addHtmlxl(); })
html部分
div class="box"> <div class="divColor"> 1 </div> <div class="divColor"> 2 </div> <div class="divColor"> 3 </div> <div class="divColor"> 4 </div> <div class="divColor"> 5 </div> <div class="divColor"> 6 </div> <div class="divColor"> 7 </div> <div class="divColor"> 8 </div> <div class="divColor"> 9 </div class="divColor"> </div>
css部分
.divColor{
width: 50px;
height: 50px;
margin: 10px;
}