这是使用纯 JavaScript 随机化类名的解决方案。
更新的答案
既然问题已经澄清,我已经更新了我的解决方案,它适合你的颜色。我已将s 设置background-color
为.card
数组中设置的颜色。这也可以很容易地完成id
,我建议不要在其中使用[]
字符,id
因为我认为我不确定这是否符合标准。
jsFiddle
var colors = [
"orange","orange","pink","pink","red","red","purple","purple",
"blue","blue","green","green","brown","brown","yellow","yellow"
];
var divs = document.getElementsByClassName("card");
while (divs.length > 0) {
var i = Math.floor(Math.random() * colors.length);
divs[0].style.backgroundColor = colors[i];
colors.splice(i, 1);
divs = [].slice.call(divs, 1);
}
原始答案
给定一个 id 数组和一组 HTML 元素,将随机id
分配给来自ids
.
jsFiddle
JavaScript
var ids = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var divs = document.getElementsByClassName("game-element");
while (divs.length > 0) {
var i = Math.floor(Math.random() * ids.length);
divs[0].id = 'item-' + ids[i];
ids.splice(i, 1);
divs = [].slice.call(divs, 1);
}
HTML
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
CSS
.game-element {
width:10px;
height:10px;
float:left;
}
#item-1 { background-color:#F00; }
#item-2 { background-color:#0F0; }
#item-3 { background-color:#00F; }
#item-4 { background-color:#FF0; }
#item-5 { background-color:#F0F; }
#item-6 { background-color:#0FF; }
#item-7 { background-color:#A0A; }
#item-8 { background-color:#0AA; }
#item-9 { background-color:#AA0; }
#item-10 { background-color:#000; }