[英]How do I iterate over the letters in these spans and assign each a color from an array in indexical order?
How do I write a simple for loop to iterate over span elements and assign each one a color from an array in an indexical order?如何编写一个简单的 for 循环来遍历 span 元素并按索引顺序从数组中为每个元素分配颜色? So the B will be red, the E orange etc.
所以B是红色的,E是橙色的等等。
const colors = ['red', 'orange', 'yellow', 'green'];
<h1> <span>B</span> <span>E</span> <span>A</span> <span>R</span> </h1>
You can first try getting all the elements using Document.querySelectorAll()
then loop through them using Array.prototype.forEach()
to set the color using Math.random()
.您可以先尝试使用
Document.querySelectorAll()
获取所有元素,然后使用Array.prototype.forEach()
遍历它们以使用Math.random()
设置颜色。
Try the following way:试试下面的方法:
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; //get all the elements const elements = document.querySelectorAll('h1 > span'); //declare an array to store all the used colors const usedColors = []; //loop through all the elements elements.forEach(function(span){ //get color randomly from the array var c = colors[Math.floor(Math.random()*colors.length)]; //check if the color is already used and loop to get new color while(usedColors.includes(c)){ //take another color from the array c = colors[Math.floor(Math.random()*colors.length)]; } //push to the used color array usedColors.push(c); //set the color to the element span.style.color = c; });
<h1> <span>B</span> <span>E</span> <span>A</span> <span>R</span> </h1>
Update: It seems simpler using the index like the following way:更新:使用索引似乎更简单,如下所示:
const colors = ['red', 'orange', 'yellow', 'green']; //get all the elements const elements = document.querySelectorAll('h1 > span'); //loop through all the elements elements.forEach(function(span, i){ //set the color to the element using index i span.style.color = colors[i]; });
<h1> <span>B</span> <span>E</span> <span>A</span> <span>R</span> </h1>
const abc = document.querySelectorAll('span');
for (let index = 0; index < abc.length; index++){
abc[index].style.color = colors[index];
This should work这应该工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.