首页 > 解决方案 > 使用 SASS 检查颜色是否包含 Alpha 通道

问题描述

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

我无法使用alphaopacity功能检查:

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

标签: sass

解决方案


这是一种天真的方法:

@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函数将只检查是否$color包含rgbawithstr-index然后返回trueor false。该函数需要一个字符串参数才能工作,因此您需要在引号之间发送颜色。

请注意,如果您还想检测十六进制颜色何时具有 alpha 通道(例如#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-length也计算#,所以条件检查它是否有 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);
}

推荐阅读