我有一张表格,其中包含可变数量的 span-Elements(Bootstrap 徽章)。其中一些具有相同的 ID,而另一些具有不同的 ID。我希望每个独特的 span-Element 都具有独特的颜色。这些颜色应该足够深以成为白色文本的良好背景,并且它们应该与其他元素尽可能不同(colofrul)。
这就是我如何使用 JavaScript 为它们应用不同的背景颜色:
// Find all span-elements with .aktiviert in #region-main
const aktiviertSpans = document.querySelectorAll("#region-main .aktiviert");
const idColors = new Map();
let hue = 0;
// loop through all span-elements
for (let i = 0; i < aktiviertSpans.length; i++) {
const span = aktiviertSpans[i];
const id = span.id;
// If ID exists, give her the existing color
if (idColors.has(id)) {
span.style.backgroundColor = idColors.get(id);
} else {
// else create a new color
const color = `hsl(${hue}, 100%, 25%)`;
idColors.set(id, color);
span.style.backgroundColor = color;
hue = (hue + (360 / idColors.size)) % 360;
}
}
现在我有两个问题: