检查颜色是否包含带有SASS的alpha通道

检查颜色是否包含带有SASS的alpha通道,sass,Sass,我需要检查颜色是否包含SASS的alpha通道 我无法使用alpha和opacity功能检查: alpha(rgba(210, 225, 221, 1)); // returns 1 alpha(#d2e1dd); // also returns 1 我想要的是这样的东西: has-alpha(rgba(210, 225, 221, 1)); // true has-alpha(#d2e1dd); // false 下面是一个简单的方法: @function has-alpha($color

我需要检查颜色是否包含SASS的alpha通道

我无法使用
alpha
opacity
功能检查:

alpha(rgba(210, 225, 221, 1)); // returns 1
alpha(#d2e1dd); // also returns 1
我想要的是这样的东西:

has-alpha(rgba(210, 225, 221, 1)); // true
has-alpha(#d2e1dd); // false

下面是一个简单的方法:

@function has-alpha($color) {
   @return if(str-index($color, "rgba"), true, false);
}

has-alpha('rgba(210, 225, 221, 1)') // true
has-alpha('#d2e1dd'); // false
has alpha
函数只需使用
str索引检查
$color
是否包含
rgba
,然后返回
true
false
。该函数需要一个字符串参数才能工作,因此需要在引号之间发送颜色

请注意,如果您还想检测何时发生故障(如
#d2e1ddff
),则需要将该功能更改为类似以下内容:

@function has-alpha($color) {
  @if str-index($color, "rgba") {
    @return true;
  } @else if str-index($color, "#") and str-length($color) == 9 {
    @return true;
  } @else {
    @return false;
  }
}
带有alpha通道的十六进制有8位数字,但此处的
str长度也计算
#
,因此条件检查它是否有9个字符而不是8个字符

你也可以用更简洁的方式来写:

@function has-alpha($color) {
  $hasAlpha: str-index($color, "rgba") or (str-index($color, "#") and str-length($color) == 9);
  @return if($hasAlpha, true, false);
}

我有一个解决方案,但它需要把颜色之间的引号,这会是一个问题,为您的用例?不,这不是一个问题,为我。