代替像 Map data structure 这样的东西Chris Eppstein 提到的 SASS 正在进行的工作,我正在尝试实现类似的东西 - 将字符串映射到相应的十六进制值,这将用于为 CSS content 属性指定一个 unicode 字符. (我正在尝试重构一些字体图标 SASS 代码。)
目前我有一些基本的东西,比如:
/*icon1 --> \F000
icon2 --> \F001
icon3 --> \F002*/
@function u-char($name) {
@if $name == icon1 {
@return "000";
} @else if $name == icon2 {
@return "001";
} @else if $name == icon3 {
@return "001";
}
}
@mixin icon-class($name) {
...
content: "\f#{u-char($name)}";
...
}
但是我实际上是在尝试映射大量字符,所以这种方法很费力。我希望能够做类似的事情:
@function u-char($name) {
$i: 0;
$itemList: item1, item2, item3;
@each $currItem in $itemList {
@if $name == item1 {
@return i-to-hex-str($i);
}
$i: $i + 1;
}
}
在 SASS 中有什么东西可以将整数转换为十六进制字符串吗?还有另一种优雅的方法吗?
最佳答案
要回答您帖子中的最后一个问题, “在 SASS 中有什么东西可以将整数转换为十六进制字符串吗?”。好吧……不是内置的,但我认为这相当清楚地完成了这个技巧,并且代码行相对较少:
/** Returns an at least one byte hex value */
@function dec-to-hex($d) {
$hexVals: "A" "B" "C" "D" "E" "F";
$base: 16;
$quotient: $d;
$result: "";
@if $d == 0 {
$result: "00";
}
@while $quotient != 0 {
$mod: $quotient % $base;
$quotient: floor($quotient / $base);
@if $mod > 9 {
$mod: nth($hexVals, $mod - 9);
}
@if $d < $base {
$result: "0" + $mod;
} @else {
$result: $mod + $result;
}
}
@return $result;
}
这不会在字符串前添加十六进制限定符(例如“0x”或“#”),但您可以将其硬编码到最后一行(@return "#"+ $result ;
),或者在调用函数时就地应用它。
关于css - 如何在 SASS 中将整数转换为十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15961089/