将LESS中的RGBA颜色定义字符串转换为颜色实例 [英] Convert rgba colour definition string in LESS to color instance

查看:1017
本文介绍了将LESS中的RGBA颜色定义字符串转换为颜色实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经解析了mixin参数,并且使用rgba函数提供了颜色.

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

现在,我想混合使用两种颜色,但是LESS mix函数需要类型为color的参数实例.

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

...而且不起作用

  1. 致电color("rgba(0,0,0,.5)")
  2. mix(@first, ~"@{second}"),其中@second是类似于rgba(0,0,0,0.5)
  3. 的字符串
  1. calling color("rgba(0,0,0,.5)")
  2. mix(@first, ~"@{second}") where @second is a string like rgba(0,0,0,0.5)

如何转换为颜色?

推荐答案

恐怕您会在LESS中找不到内置函数来完成此任务.

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

color()函数参数必须为十六进制或其简写形式.

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

但是您可以进一步使用javascript 将该字符串解析为

But you can further parse the string with javascript to

  • 提取单个的r,g,b和alpha值,
  • 将各个值传递给rgba()函数以获取类型的变量 颜色.
  • extract the individual r,g,b and alpha values,
  • pass the individual values to the rgba() function to get a variable of type color.

您可以执行原始解析的第一步. 如果您需要在LESS中完成所有操作,则可以执行以下操作:

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]`));

很遗憾,不能将字符串直接读取到rgba()或类似函数中,因为它们需要多个参数.即使使用字符串转义(例如~),输出也将格式化为单个变量(~"a, b, c"变为a, b, c并用作css的单个输出字符串),因此我们需要单独获取每个值并将其传递到rgba()函数的相应参数/变量.使用功能unit(),我们将字符串转换为可以进一步使用的数字.

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.

例如:

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

产生 CSS :

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

这篇关于将LESS中的RGBA颜色定义字符串转换为颜色实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆