[英]How to change colour of each element within a class
Let's say I had the following code假设我有以下代码
<div class="elements">
<span></span>
<span></span>
<span></span>
</div>
<style>
.span {
background-color: red;
width: 50px;
height: 50px;
}
</style>
This would produce 3 red squares within the elements
div.这将在elements
div 中生成 3 个红色方块。 Would there be a way for me to assign each span
element a random colour independent of each other?有没有办法让我为每个span
元素分配一个相互独立的随机颜色? So when I load the page, one might be yellow, another blue, and the last could be red所以当我加载页面时,一个可能是黄色的,另一个是蓝色的,最后一个可能是红色的
to random assign you can use javascript随机分配你可以使用 javascript
function getRandomColor() { var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } document.querySelectorAll('span').forEach(x=>{ x.style.color= getRandomColor(); })
<div class="elements"> <span>a</span> <span>b</span> <span>c</span> </div> <style> span { width: 50px; height: 50px; } </style>
Use foreach and an array to define your background colors run a function to shuffle the array and find a unique color使用 foreach 和数组来定义你的背景 colors 运行 function 来打乱数组并找到唯一的颜色
//get the element list using the tag and parent class let spans = document.querySelectorAll('.elements span'); //assign colors to an array let colors = ['red', 'green', 'blue', 'purple', 'orange', 'pink', 'yellow', 'teal'] const randomElement = colors[Math.floor(Math.random() * colors.length)]; //shuffle the array of colors function* shuffle(colors) { var i = colors.length; //run while loop and decrement the array colors while (i--) { //splice using a random number wihtin the array to find unique values yield colors.splice(Math.floor(Math.random() * (i+1)), 1)[0]; } } //redefine the color array by shuffling it var ranCols = shuffle(colors); //iterate over the element list spans.forEach(function(value) { //Assign the style backgroundColor to the element/s value.style.backgroundColor = ranCols.next().value; })
.span { background-color: red; width: 50px; height: 50px; }
<div class="elements"> <span>Test</span> <span>Test</span> <span>Test</span> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.