javascript - 如何遍历这些跨度中的字母并按索引顺序从数组中为每个字母分配颜色?
问题描述
如何编写一个简单的 for 循环来遍历 span 元素并按索引顺序从数组中为每个元素分配颜色?所以B是红色的,E是橙色的等等。
const colors = ['red', 'orange', 'yellow', 'green'];
<h1>
<span>B</span>
<span>E</span>
<span>A</span>
<span>R</span>
</h1>
解决方案
您可以先尝试使用 获取所有元素,Document.querySelectorAll()
然后使用 遍历它们Array.prototype.forEach()
以设置颜色Math.random()
。
试试下面的方法:
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>
更新:使用索引似乎更简单,如下所示:
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>