代码之家  ›  专栏  ›  技术社区  ›  Amin Shah Gilani

如何访问数据属性的值并在CSS声明中使用它

  •  0
  • Amin Shah Gilani  · 技术社区  · 6 年前

    data-attribute 把它放在申报单里面?

    例如,假设我有以下HTML:

    <div class="black box">
      <div data-color="green">
        This text should be green
      </div>
    
      <div data-color="red">
        This text should be red
      </div>
    
      <div data-color="white">
        This text should be white
      </div>
    </div>
    

    因此:

    Rendered HTML

    使用以下CSS:

    /* Ignore this */
    .black.box {
      background-color: black;
    }
    
    
    /* Refactor the three rules below into a single rule */
    div[data-color="green"] {
      color: green;
    }
    
    div[data-color="red"] {
      color: red;
    }
    
    div[data-color="white"] {
      color: white;
    }
    

    div[data-color=VALUE] {
      color: VALUE;
    }
    

    https://jsfiddle.net/gilani/54de0zn6/7/

    1 回复  |  直到 6 年前
        1
  •  1
  •   Temani Afif    6 年前

    在这种特殊情况下,使用内联样式是一种解决方案,因为这些值已经内联添加:

    .black {
      background:black;
      font-size:30px;
    }
    <div class="black box">
      <div style="color:green">
        This text should be green
      </div>
    
      <div style="color:red">
        This text should be red
      </div>
    
      <div style="color:white">
        This text should be white
      </div>
    </div>

    您还可以考虑在更复杂的情况下使用CSS变量(也依赖于内联样式)

    .black {
      background:black;
      font-size:30px;
    }
    
    .black > div {
      color:var(--c);
      border:5px solid var(--c);
    }
    <div class="black box">
      <div style="--c:green">
        This text should be green
      </div>
    
      <div style="--c:red">
        This text should be red
      </div>
    
      <div style="--c:white">
        This text should be white
      </div>
    </div>