我有一个scss mixin,它动态地将颜色应用于svg:
$someColor: #ff3300;
@include successCheck($someColor);
@mixin successCheck($colour) {
background-image: url('data:image/svg+xml;utf8,<svg viewBox="0 -46 417.813 417" xmlns="http://www.w3.org/2000/svg"><path fill="#{$colour}" d="M159.988 318.582c-3.988 4.012-9.43 6.25-15.082 6.25s-11.094-2.238-15.082-6.25L9.375 198.113c-12.5-12.5-12.5-32.77 0-45.246l15.082-15.086c12.504-12.5 32.75-12.5 45.25 0l75.2 75.203L348.104 9.781c12.504-12.5 32.77-12.5 45.25 0l15.082 15.086c12.5 12.5 12.5 32.766 0 45.246zm0 0"/></svg>');
}
我看到的问题是,通过的颜色是十六进制值(#ff3300
(,而在背景图像数据url中,#
导致了问题,因为在数据url中它应该是%23
。我不能修改原始scss变量,因为它在其他地方被用作常规颜色。
我确实尝试过用string-slice($color, 1)
来删除#
,但没有成功。是否可以将十六进制颜色作为变量传递给svg背景图像?
在SASS中将颜色值转换为字符串确实非常难看!
(1(字符串替换#
到%23
在URL中不起作用
您将字符#
替换为%23
的想法在形式上是正确的。但是这种方法在URL中不起作用,因为十六进制颜色根本不与颜色字符串/值相关联。
要自己检查,这里是SASS方法,使用#
:的"%23"将十六进制颜色转换为字符串
//### SASS: transfer color to string
$someColor: #ff3300;
$string: str-slice(#{$someColor}, 2,7);
$string: '%27' + $string;
// becomes: %27ff3300
// --> test it in your mixin
// --> or for testing write the color string direct to the CSS
// --> it will not be accepted as color
(2(解决方法:将rgb颜色字符串写入URL
URL表示法接受rgb颜色。
但挑战在于,SASS将以rgb((形式给出的颜色转换为十六进制代码。所以,你需要一个小技巧,让SASS将颜色代码作为字符串。使用SASS函数red() / green() / blue()
构建字符串并部分连接值。
以下是您的mixin示例:
//SASS
@mixin successCheck($color) {
// transfer given (hex-)color to rga-string
$color: 'rgb(' + red($color) + ',' + green($color) + ',' + blue($color) + ')';
// include string variable to your code
background-image: url('data:image/svg+xml;utf8,<svg viewBox="0 -46 417.813 417" xmlns="http://www.w3.org/2000/svg"><path fill="#{$color}" d="M159.988 318.582c-3.988 4.012-9.43 6.25-15.082 6.25s-11.094-2.238-15.082-6.25L9.375 198.113c-12.5-12.5-12.5-32.77 0-45.246l15.082-15.086c12.504-12.5 32.75-12.5 45.25 0l75.2 75.203L348.104 9.781c12.504-12.5 32.77-12.5 45.25 0l15.082 15.086c12.5 12.5 12.5 32.766 0 45.246zm0 0"/></svg>');
}
// will become CSS:
background-image: url('data:image/svg+xml;utf8,<svg viewBox="0 -46 417.813 417" xmlns="http://www.w3.org/2000/svg"><path fill="rgb(255,51,0)" d="M159.988 318.582c-3.988 4.012-9.43 6.25-15.082 6.25s-11.094-2.238-15.082-6.25L9.375 198.113c-12.5-12.5-12.5-32.77 0-45.246l15.082-15.086c12.504-12.5 32.75-12.5 45.25 0l75.2 75.203L348.104 9.781c12.504-12.5 32.77-12.5 45.25 0l15.082 15.086c12.5 12.5 12.5 32.766 0 45.246zm0 0"/></svg>');
/// ... and make your svg hook in red color ;-)