gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:44:06 26 4
gpt4 key购买 nike

如何修改此脚本并防止 .test-box 元素具有与 sibling 相同的颜色,前提是它们是 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)];
});

}

最佳答案

改为打乱数组

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>

关于javascript - 防止两个元素具有相同的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51391625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com