伙计们,我想获得 2 种随机颜色,并从这 2 种选择的颜色中为我的 4 个 div 制作 background-color
。
我想要的是如何确保将 2 种颜色分别用作 background-color
2 次。
(在我的代码中,有时我会看到一种随机颜色作为背景颜色 3 次。)
$(function() {
function getRandomArrayElements(arr, count) {
var shuffled = arr.slice(0),
i = arr.length,
min = i - count,
temp, index;
while (i-- > min) {
index = Math.floor((i + 1) * Math.random());
temp = shuffled[index];
shuffled[index] = shuffled[i];
shuffled[i] = temp;
}
return shuffled.slice(min);
}
var randomColor1 = '#' + (Math.random() * 0xFFFFFF << 0).toString(16);
var randomColor2 = '#' + (Math.random() * 0xFFFFFF << 0).toString(16);
var colors = [randomColor1, randomColor2];
$(".first").css("background-color", getRandomArrayElements(colors, 1));
$(".second").css("background-color", getRandomArrayElements(colors, 1));
$(".third").css("background-color", randomColor1);
$(".fourth").css("background-color", randomColor2);
});
div {
width: 100px;
height: 100px;
border: solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first"></div>
<div class="second"></div>
<div class="third"></div>
<div class="fourth"></div>
最佳答案
这个怎么样:
function removeRandomElement(colors) {
return colors.splice(Math.floor(Math.random() * colors.length), 1)[0];
}
var colors = [randomColor1, randomColor1, randomColor2, randomColor2];
$(".first").css("background-color", removeRandomElement(colors));
$(".second").css("background-color", removeRandomElement(colors));
$(".third").css("background-color", removeRandomElement(colors));
$(".fourth").css("background-color", removeRandomElement(colors));
关于javascript - 我怎样才能确保每 2 种随机颜色被使用两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39064066/