防止两个元素具有相同的颜色?

时间:2018-07-17 23:44:59

标签: javascript

如何修改此脚本并防止.test-box元素具有与兄弟姐妹相同的颜色,只要它们为4 .test-boxes

var colors = [
    "rgb(100, 50, 100)",
    "rgb(200, 100, 200)",
    "rgb(150, 75, 150)",
    "rgb(230, 80, 230)",
];

function colorsFunction() {
    // Get all the elements that use the "view" class but do it using querySelectorAll
    var divs = Array.prototype.slice.call(document.querySelectorAll(".test-box"));

    // Loop through the array of divs
    divs.forEach(function(div){
        // Set the background color of each div
        div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
    });

}

2 个答案:

答案 0 :(得分:2)

随机播放数组,然后使用forEach提供的索引,而不是随机的索引:

function colorsFunction() {
    var divs = Array.prototype.slice.call(document.querySelectorAll(".test-box"));

    // You can use any shuffling method you like, for simplicity we are using this less pwerful one. To be honnest I don't know why you want to shuffle the array anyway, can't you just use the colors as they are in the array?
    colors.sort(function(a, b) { return Math.random() - 0.5; });

    // use the index i provided by forEach
    divs.forEach(function(div, i) {
        div.style.backgroundColor = colors[i];
    });

}

注意:上面的代码中使用的改组算法不是一种很好的算法,但是它非常简洁,因此我使用了它。如果您想要更好的选择,请另选SO question。我之所以使用它,是因为我仍然不相信您根本不需要重新整理阵列。

答案 1 :(得分:2)

改组数组

var colors = [
  "rgb(100, 50, 100)",
  "rgb(200, 100, 200)",
  "rgb(150, 75, 150)",
  "rgb(230, 80, 230)",
];

function colorsFunction() {
  colors.sort(function() { return Math.random() - 0.5 })
  var divs = Array.prototype.slice.call(document.querySelectorAll(".test-box"));

  // Loop through the array of divs
  divs.forEach(function(div, i) {
    // Set the background color of each div
    div.style.backgroundColor = colors[i];
  });

}

colorsFunction()
.test-box {
  height: 50px
}
<button onclick="colorsFunction()">Change colors</button>
<div class="test-box"></div>
<div class="test-box"></div>
<div class="test-box"></div>
<div class="test-box"></div>