Damian 给出的答案还不错,但我更喜欢更容易维护的东西。基本上,我还需要准备一种样式,我可以根据主题更改颜色,因此 png 图像(在 base64 中)不是一个好的选择。
这就是使用 SVG 的方法:
select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
/* SVG background image */
background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='%23FF0000'><polygon points='20,0 80,0 50,52'/></svg>");
background-size: 12px;
background-position-x: right;
background-position-y: calc(100% - 10px);
background-repeat: no-repeat;
}
我使用 scss 根据变量生成样式,所以我想使用$base-font-color 作为三角形的颜色。问题在于编码。
Chrome 可以处理简单的.. fill='"+ $base-font-color +"' .. in:
background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='"+ $base-font-color +"'><polygon points='20,0 80,0 50,52'/></svg>");
但 Firefox 需要 %23。这是一个问题,因为我将颜色存储在变量中:$base-font-color: #3e4f5e; 而不是$base-font-color: '3e4f5e'。解决方案是 convert color to string 并使用 string replacement 将 '#' 替换为 '%23'
@function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
}
@function to-string($value) {
@return inspect($value);
}
select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
/* SVG background image */
background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='"+ str-replace(to-string($base-font-color), '#', '%23') +"'><polygon points='20,0 80,0 50,52'/></svg>");
background-size: 12px;
background-position-x: right;
background-position-y: calc(100% - 10px);
background-repeat: no-repeat;
}