【问题标题】:Change background-color if class contains a value如果类包含值,则更改背景颜色
【发布时间】:2022-01-06 13:34:02
【问题描述】:

我想知道当一个类具有特定值时是否可以更改它的背景颜色。

示例:如果元素包含 '1',则将 bg-color 更改为红色,如果包含 '2',则将 bg-color 更改为绿色,等等。

HTML:

<div class="skill-points"> 1 </div> <!-- BG color = red -->
<div class="skill-points"> 2 </div> <!-- BG color = green -->
<div class="skill-points"> 3 </div> <!-- BG color = yellow -->

CSS:

.skill-points {
width: 50px;
padding: 4px;
margin: 4px;
border: 1px solid #000;
text-align: center;
}

我应该如何编写我的 JavaScript 代码来实现这个效果?

【问题讨论】:

    标签: javascript background-color


    【解决方案1】:

    您可以在集合中获取所有相关的class 元素(使用getElementsByClassName),然后将其转换为array(使用spread 运算符)。然后,您可以使用 style.backgroundColor 属性分配背景颜色。

    我使用了一个映射对象,它很有用,否则您也可以进行单独的if 检查。 innerText 是您可以用来比较 HTML 元素的内部 Text 的属性。

    let mapping = {
    '1' : 'red', '2' : 'green' , '3': 'blue' };
    
    [...document.getElementsByClassName('skill-points')].forEach( x => {
    x.style.backgroundColor = mapping[x.innerText];
    });
    .skill-points {
    width: 50px;
    padding: 4px;
    margin: 4px;
    border: 1px solid #000;
    text-align: center;
    }
    <div class="skill-points"> 1 </div> <!-- BG color = red -->
    <div class="skill-points"> 2 </div> <!-- BG color = green -->
    <div class="skill-points"> 3 </div>

    【讨论】:

      【解决方案2】:

      ...几乎所有人都这么说。这是我的方法:

      const valueClassMap = {
        1: "bg-red",
        2: "bg-green",
        3: "bg-yellow"
      };
        
      document.querySelectorAll(".skill-points").forEach(el => {
        const content = el.textContent.trim();
        if(valueClassMap.hasOwnProperty(content)){
          el.classList.add(valueClassMap[content]);
        } 
      });
      .bg-red{ background: red }
      .bg-green{ background: green }
      .bg-yellow{ background:yellow }
      <div class="skill-points"> 1 </div> <!-- BG color = red -->
      <div class="skill-points"> 2 </div> <!-- BG color = green -->
      <div class="skill-points"> 3 </div> <!-- BG color = yellow -->

      【讨论】:

        【解决方案3】:

        首先你需要检查 class 是否有 value 。 你必须知道 getElementsByClassName() 返回一个数组,因此您必须访问第一个元素(如果有的话)。然后尝试通过这个 javascript 代码访问 value 属性,该代码根据值的长度检测值。

          var id = document.getElementsByClassName("classname");
          if (id.length > 0) {
          var x = id[0].value;
          alert(id[0].value);
          }
        

        然后是您要更改检测到的类的背景的部分。 您可以将 if 条件设为

           if x = x {
           document.getElementsByClassName('classname').style.backgroundColor = "red";
           }
        

        【讨论】:

          【解决方案4】:

          只需遍历您的元素,检查innerText,然后设置元素样式。

          document.querySelectorAll('.skill-points').forEach(div => {
            if (div.innerText.contains('1')) div.style.backgroundColor = 'red';
            ...
          });
          

          【讨论】:

          • HTMLCollection 没有 forEach 方法。
          • @Unmitigated 正确,谢谢 - 更新
          【解决方案5】:

          1)您可以使用textContent获取文本并将其匹配并将颜色设置为

          const allSkillPoints = document.querySelectorAll(".skill-points");
          
          allSkillPoints.forEach(el => {
            const text = +el.textContent.trim();
            if (text === 1) el.style.backgroundColor = "red";
            else if (text === 2) el.style.backgroundColor = "green";
            else if (text === 3) el.style.backgroundColor = "yellow";
          })
          .skill-points {
            width: 50px;
            padding: 4px;
            margin: 4px;
            border: 1px solid #000;
            text-align: center;
          }
          <div class="skill-points"> 1 </div>
          <!-- BG color = red -->
          <div class="skill-points"> 2 </div>
          <!-- BG color = green -->
          <div class="skill-points"> 3 </div>
          <!-- BG color = yellow -->

          2) 你也可以在这里使用Map

          const allSkillPoints = document.querySelectorAll(".skill-points");
          
          const map = new Map()
          map.set(1, "red")
            .set(2, "green")
            .set(3, "yellow");
          
          allSkillPoints.forEach(el => {
            const text = +el.textContent.trim();
            el.style.backgroundColor = map.has(text) ? map.get(text) : "white";
          })
          .skill-points {
            width: 50px;
            padding: 4px;
            margin: 4px;
            border: 1px solid #000;
            text-align: center;
          }
          <div class="skill-points"> 1 </div>
          <!-- BG color = red -->
          <div class="skill-points"> 2 </div>
          <!-- BG color = green -->
          <div class="skill-points"> 3 </div>
          <!-- BG color = yellow -->

          【讨论】:

          • 您无需将NodeList 转换为数组即可调用forEach
          • @Unmitigated 是的,谢谢。
          猜你喜欢
          • 2021-03-07
          • 2012-05-23
          • 1970-01-01
          • 1970-01-01
          • 2023-04-01
          • 1970-01-01
          • 2021-02-01
          • 2015-05-07
          • 2019-05-22
          相关资源
          最近更新 更多