使用 Javascript 给所有元素不同的背景颜色

问题描述 投票:0回答:0

我有一张表格,其中包含可变数量的 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;
    }
}

现在我有两个问题:

  1. 这是一个好方法还是有更好的方法?一旦存在太多条目,是否可以包含亮色和黑色文本?
  2. 出于某种原因,前两个条目具有相同的背景颜色(参见“Max”和“Susanne”)。我该如何解决这个问题?
javascript html css twitter-bootstrap background-color
© www.soinside.com 2019 - 2024. All rights reserved.