SASS HEX 到 RGB,不带“rgb”前缀

问题描述 投票:0回答:3

问题:

是否有 SASS 函数/技术可以将十六进制值转换为简单 RGB 字符串。

这里的“简单”意味着只是一个字符串,而不用

rgb()
括起来?

例如:

#D50000 --> "213,0,0"


为什么我需要这个:

我使用 Material Design Lite 作为我的 UI“框架”。更具体地说,我使用的是 SASS 版本,因此我可以根据应用程序的样式指南调整颜色变量。

出于某种原因,MDL

_variables.scss
中的颜色变量采用以下格式进行颜色定义:

$color-primary: "0,0,0" !default; // supposed to be black

这真的非常非常奇怪。我预计,最多,类似的事情

$color-primary: rgba(0,0,0,1) !default;

我的颜色变量存储在另一个名为

_globals.scss
的文件中,我在其中以常规十六进制格式存储变量,以便我可以轻松地在其他地方重用它们:

$brand-primary: #FA3166;
$brand-primary-dark: #E02C59;

我不想定义两倍的颜色(1 个十六进制和 1 个 MDL 兼容的 RGB 字符串),因此我需要将十六进制转换为 RGB 字符串。

sass material-design material-design-lite
3个回答
8
投票

@nicholas-kyriakides 的答案工作得很好,但这里有一个使用 Sass 插值的更简洁的函数。

@function hexToRGBString($hexColor) {
  @return "#{red($hexColor)},#{green($hexColor)},#{blue($hexColor)}";
}

您可以显式传入十六进制,也可以从 rgb() 或 rgba() 传入不透明度为 1 的十六进制。

例如:

$color-white: hexToRGBString(#fff) => "255,255,255"
$color-white: hexToRGBString(rgb(255,255,255)) => "255,255,255"
$color-white: hexToRGBString(rgba(#fff,1)) => "255,255,255"

1
投票

我用 SASS 函数破解了它:

@function hexToString($hexColor) {

  // 0.999999 val in alpha actually compiles to 1.0
  $rgbaVal: inspect(rgba($hexColor,0.9999999));

  // slice substring between 'rgba(' and '1.0)' 
  @return str-slice($rgbaVal, 6, str-length($rgbaVal)-6);

}

用途:

$brand-primary: #333;
$color-primary: hexToString($brand-primary);

我认为 MDL 团队打算采用不同的方式来自定义调色板,但我错过了它,所以如果有人知道更好的方法来自定义 MDL 的调色板,我愿意接受建议。不管怎样,这解决了原来的问题。


0
投票

对于使用 Bootstrap 并遇到此问题的任何人,他们有一个内置函数可以执行此操作。

@import "node_modules/bootstrap/scss/functions";

$brand-primary: #333;
$color-primary: to-rgb($brand-primary);

如果你深入研究其来源,就会发现很简单:

@function to-rgb($value) {
  @return red($value), green($value), blue($value);
}
© www.soinside.com 2019 - 2024. All rights reserved.