【问题标题】:Tailwind: from green to red color depend on percentage using Tailwind cssTailwind:从绿色到红色取决于使用 Tailwind css 的百分比
【发布时间】:2021-07-19 17:00:53
【问题描述】:

我需要基于进度变量的从绿色到红色的背景颜色映射(例如 fiddle)。

function getColor(value){
    //value from 0 to 1
    var hue=((1-value)*120).toString(10);
    return ["hsl(",hue,",100%,50%)"].join("");
}
var len=20;
for(var i=0; i<=len; i++){
    var value=i/len;
    var d=document.createElement('div');
    d.textContent="value="+value;
    d.style.backgroundColor=getColor(value);
    document.body.appendChild(d);
}

正如已经回答 here on Stackoverflow 但使用 Tailwind CSS。这可能吗?

【问题讨论】:

    标签: css tailwind-css


    【解决方案1】:

    当前的解决方案,即时生成颜色值。用 Tailwindcss 来伪造这样的效果,我认为制作一组 11 种颜色来使用是合理的。可以将它们称为color-range-0, color-range-1,...color-range-10,然后通过进行此修改直接分配它们:

    //old:
    d.style.backgroundColor=getColor(value);
    
    //new:
    d.classList.add("bg-color-range-" + i);
    

    这就是tailwindcss配置文件的内容:

    module.exports = {
      theme: {
        extend: {
          colors: {
            "color-range": {
              0: "#00FF00",
              1: "#33ff00",
              2: "#66ff00",
              3: "#99ff00",
              4: "#ccff00",
              5: "#ffff00",
              6: "#ffcc00",
              7: "#ff9900",
              8: "#ff6600",
              9: "#ff3300",
              10: "#ff0000",
            }
          },
        },
      },
      variants: {},
      plugins: [],
    }
    

    结果会是这样的:

    请记住,如果您使用 postcss 删除未使用的样式,则需要将这些样式的名称保留在 html 文件的 cmets 中的某个位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 2014-02-23
      • 2021-09-02
      • 2021-06-09
      相关资源
      最近更新 更多