简体   繁体   English

Tailwind:从绿色到红色取决于使用 Tailwind css 的百分比

[英]Tailwind: from green to red color depend on percentage using Tailwind css

I need background color map from green to red based on a progress variable (like in this 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);
}

As already answered here on Stackoverflow but using Tailwind CSS.正如已经在 Stackoverflow 上回答的那样但使用 Tailwind CSS。 Is that possible?那可能吗?

The current solution, generates color value on the fly.当前的解决方案是动态生成颜色值。 To fake such effect with Tailwindcss, I think it is reasonable to make a set of 11 colors to use.为了用 Tailwindcss 来伪造这样的效果,我认为制作一组 11 种颜色来使用是合理的。 They can be called color-range-0, color-range-1,...color-range-10 and then in assign them directly by making this modification:它们可以称为color-range-0, color-range-1,...color-range-10 ,然后通过进行以下修改直接分配它们:

//old:
d.style.backgroundColor=getColor(value);

//new:
d.classList.add("bg-color-range-" + i);

and this is what should go to tailwindcss config file:这就是应该转到 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: [],
}

Result would be something like this:结果将是这样的:

在此处输入图片说明

Just keep in mind if you are using postcss to remove unused styles, you need to keep the name of these styles somewhere in comments in your html file.请记住,如果您使用 postcss 删除未使用的样式,则需要在 html 文件的注释中保留这些样式的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM