Convert rgba colour definition string in LESS to color instance

最后都变了- 提交于 2020-01-04 09:07:20

问题


Suppose I've parsed my mixin parameters and colours are provided using rgba function.

Now I would like to mix two of those colours, but LESS mix function requires parameter instances of type color.

What I tried

...and doesn't work

  1. calling color("rgba(0,0,0,.5)")
  2. mix(@first, ~"@{second}") where @second is a string like rgba(0,0,0,0.5)

How do I convert to color?


回答1:


I'm afraid you won't find a built in function to do this in LESS.

The color() functions argument needs to be a hexadecimal or its shorthand representation.

But you can further parse the string with javascript to

  • extract the individual r,g,b and alpha values,
  • pass the individual values to the rgba() function to get a variable of type color.

You could do the first step in your original parsing. If you need to do all in LESS you can do something like this:

  @color1: "rgba(255, 255, 0, 0.5)";
  @color2: ~`@{color1}.replace(/^(rgb|rgba)\(/,'[').replace(/\)$/,']').replace(/\s/g,'')`;
  @color3: rgba(unit(`@{color2}[0]`),unit(`@{color2}[1]`),unit(`@{color2}[2]`),unit(`@{color2}[3]`));

Unfortunately the string can not be directly read into the rgba() or similar functions as they expect multiple arguments. Even with string escaping (eg. ~) the output gets formated as a single variable (~"a, b, c" becomes a, b, c and acts as a single output string for the css), so we need to get each value individually and pass it to its respective argument/variable of the rgba() function. Using the function unit() we transform a string to a number that can be used further.

For example:

  @color4: mix(red,@color3);
  .test {
      color: @color4;
  }

resulting in CSS:

  .test{
    color: rgba(255, 64, 0, 0.75);
  }


来源:https://stackoverflow.com/questions/15681931/convert-rgba-colour-definition-string-in-less-to-color-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!