sass - 使用 SASS 检查颜色是否包含 Alpha 通道
问题描述
我需要检查颜色是否包含带有 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
函数将只检查是否$color
包含rgba
withstr-index
然后返回true
or 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);
}
推荐阅读
- mqtt - MQTT 中的请求/响应是否可以实现单呼叫、多应答模式?
- android - 带有三角形尾巴的圆角矩形
- php - 如何在字符串类型的数据库列中插入数组?
- python - 从 csv 文件读取图形时出现问题。不会读取 CSV 文件的标题
- r - 如何使用 dplyr 扩展和插值数据帧中的分组数据,每个组的插值点数量相等?
- html - 使用 nbconvert 时如何更改代码背景颜色?
- php - 如何使用来自数据库的动态输入在 select 语句中声明选定选项?
- java - 如何测试 Hibernate JPA 持久层?
- ios - 在将统一构建集成到现有 xcode 项目中时获取“未找到架构 arm64 的符号”
- java - 如何使用 dcm4che 在 DICOM 中创建新/自定义标签?